From 44538a62752ef685844c0da4fd85af532fb632dc Mon Sep 17 00:00:00 2001 From: Reto Schnyder Date: Sat, 12 Mar 2022 13:40:44 +0100 Subject: [PATCH] Return time as period for relative times with hours/minutes/seconds --- dateparser/freshness_date_parser.py | 13 +++++++++---- tests/test_freshness_date_parser.py | 6 ++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/dateparser/freshness_date_parser.py b/dateparser/freshness_date_parser.py index 4a64f4ce5..27f7d7fd8 100644 --- a/dateparser/freshness_date_parser.py +++ b/dateparser/freshness_date_parser.py @@ -92,7 +92,7 @@ def apply_time(dateobj, timeobj): else: now = datetime.now(self.get_local_tz()) - date, period = self._parse_date(date_string, now, settings.PREFER_DATES_FROM) + date, period = self._parse_date(date_string, now, settings) if date: old_date = date @@ -112,7 +112,7 @@ def apply_time(dateobj, timeobj): return date, period - def _parse_date(self, date_string, now, prefer_dates_from): + def _parse_date(self, date_string, now, settings): if not self._are_all_words_units(date_string): return None, None @@ -120,7 +120,12 @@ def _parse_date(self, date_string, now, prefer_dates_from): if not kwargs: return None, None period = 'day' - if 'days' not in kwargs: + if settings.RETURN_TIME_AS_PERIOD: + for k in ['seconds', 'minutes', 'hours']: + if k in kwargs: + period = 'time' + break + if period != 'time' and 'days' not in kwargs: for k in ['weeks', 'months', 'years']: if k in kwargs: period = k[:-1] @@ -129,7 +134,7 @@ def _parse_date(self, date_string, now, prefer_dates_from): if ( re.search(r'\bin\b', date_string) - or re.search(r'\bfuture\b', prefer_dates_from) + or re.search(r'\bfuture\b', settings.PREFER_DATES_FROM) and not re.search(r'\bago\b', date_string) ): date = now + td diff --git a/tests/test_freshness_date_parser.py b/tests/test_freshness_date_parser.py index 41854adb2..df94256b5 100644 --- a/tests/test_freshness_date_parser.py +++ b/tests/test_freshness_date_parser.py @@ -45,6 +45,12 @@ def now_with_timezone(self, tzinfo): # English dates param("yesterday", ago={'days': 1}, period='day'), param("yesterday at 11:30", ago={'hours': 23}, period='time'), + param("2 days ago", ago={'days': 2}, period='day'), + param("48 hours ago", ago={'hours': 48}, period='time'), + param("today", ago={'days': 0}, period='day'), + param("now", ago={'seconds': 0}, period='time'), + param("4 weeks 2 hours ago", ago={'weeks': 4, 'hours': 2}, period='time'), + param("3 days 2 hours ago", ago={'days': 3, 'hours': 2}, period='time'), ]) def test_relative_past_dates_with_time_as_period(self, date_string, ago, period): self.given_parser(settings={'NORMALIZE': False, 'RETURN_TIME_AS_PERIOD': True})