From b3ba9e3338db83123e08f27a9cc0fdb50656b78e Mon Sep 17 00:00:00 2001 From: Yongjie Zhao Date: Wed, 2 Jun 2021 14:26:37 +0100 Subject: [PATCH] fix: time parser truncate to first day of year/month (#14945) --- superset/utils/date_parser.py | 3 ++- tests/utils/date_parser_tests.py | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/superset/utils/date_parser.py b/superset/utils/date_parser.py index 30fce841b793a..42625e66a2795 100644 --- a/superset/utils/date_parser.py +++ b/superset/utils/date_parser.py @@ -79,7 +79,8 @@ def parse_human_datetime(human_readable: str) -> datetime: if re.search(x_periods, human_readable, re.IGNORECASE): raise TimeRangeUnclearError(human_readable) try: - dttm = parse(human_readable) + default = datetime(year=datetime.now().year, month=1, day=1) + dttm = parse(human_readable, default=default) except (ValueError, OverflowError) as ex: cal = parsedatetime.Calendar() parsed_dttm, parsed_flags = cal.parseDT(human_readable) diff --git a/tests/utils/date_parser_tests.py b/tests/utils/date_parser_tests.py index 2d5cb2264de62..ad87f40dc8218 100644 --- a/tests/utils/date_parser_tests.py +++ b/tests/utils/date_parser_tests.py @@ -35,6 +35,10 @@ def mock_parse_human_datetime(s): if s == "now": return datetime(2016, 11, 7, 9, 30, 10) + elif s == "2018": + return datetime(2018, 1, 1) + elif s == "2018-9": + return datetime(2018, 9, 1) elif s == "today": return datetime(2016, 11, 7) elif s == "yesterday": @@ -153,6 +157,14 @@ def test_datetime_eval(self): expected = datetime(2016, 11, 7) self.assertEqual(result, expected) + result = datetime_eval("datetime('2018')") + expected = datetime(2018, 1, 1) + self.assertEqual(result, expected) + + result = datetime_eval("datetime('2018-9')") + expected = datetime(2018, 9, 1) + self.assertEqual(result, expected) + # Parse compact arguments spelling result = datetime_eval("dateadd(datetime('today'),1,year,)") expected = datetime(2017, 11, 7)