Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add quarter unit to datetrunc #17416

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ dateadd(datetime("2020-03-01"), 2, day)`}</code>
<h4>{t('Syntax')}</h4>
<pre>
<code>{`datetrunc([datetime], [dateunit])
dateunit = (year | month | week)`}</code>
dateunit = (year | quarter | month | week)`}</code>
</pre>
<h4>{t('Example')}</h4>
<pre>
Expand Down
7 changes: 5 additions & 2 deletions superset/utils/date_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from time import struct_time
from typing import Dict, List, Optional, Tuple

import pandas as pd
import parsedatetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
Expand Down Expand Up @@ -322,10 +323,12 @@ def eval(self) -> datetime:
dttm = dttm.replace(
month=1, day=1, hour=0, minute=0, second=0, microsecond=0
)
if unit == "quarter":
dttm = pd.Period(pd.Timestamp(dttm), freq="Q").to_timestamp()
elif unit == "month":
dttm = dttm.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
elif unit == "week":
dttm = dttm - relativedelta(days=dttm.weekday())
dttm -= relativedelta(days=dttm.weekday())
dttm = dttm.replace(hour=0, minute=0, second=0, microsecond=0)
elif unit == "day":
dttm = dttm.replace(hour=0, minute=0, second=0, microsecond=0)
Expand Down Expand Up @@ -443,7 +446,7 @@ def datetime_parser() -> ParseResults: # pylint: disable=too-many-locals
+ Group(
date_expr
+ comma
+ (YEAR | MONTH | WEEK | DAY | HOUR | MINUTE | SECOND)
+ (YEAR | QUARTER | MONTH | WEEK | DAY | HOUR | MINUTE | SECOND)
+ ppOptional(comma)
)
+ rparen
Expand Down
4 changes: 4 additions & 0 deletions tests/integration_tests/utils/date_parser_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,10 @@ def test_datetime_eval(self):
expected = datetime(2016, 1, 1, 0, 0, 0)
self.assertEqual(result, expected)

result = datetime_eval("datetrunc(datetime('now'), quarter)")
expected = datetime(2016, 10, 1, 0, 0, 0)
self.assertEqual(result, expected)

result = datetime_eval("datetrunc(datetime('now'), month)")
expected = datetime(2016, 11, 1, 0, 0, 0)
self.assertEqual(result, expected)
Expand Down