Skip to content

Commit

Permalink
feature: Add quarter unit to datetrunc (#17416)
Browse files Browse the repository at this point in the history
Co-authored-by: John Bodley <john.bodley@airbnb.com>
  • Loading branch information
2 people authored and AAfghahi committed Jan 10, 2022
1 parent eff362f commit a50d2ea
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
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

0 comments on commit a50d2ea

Please sign in to comment.