diff --git a/maya/core.py b/maya/core.py index 042bfd8..423fb2c 100644 --- a/maya/core.py +++ b/maya/core.py @@ -578,7 +578,7 @@ def now(): return MayaDT(epoch=epoch) -def when(string, timezone='UTC'): +def when(string, timezone='UTC', prefer_past=False): """"Returns a MayaDT instance for the human moment specified. Powered by dateparser. Useful for scraping websites. @@ -589,10 +589,15 @@ def when(string, timezone='UTC'): Keyword Arguments: string -- string to be parsed timezone -- timezone referenced from (default: 'UTC') + prefer_past -- prefer parsing ambiguous date as in the past """ - dt = dateparser.parse(string, - settings={'TIMEZONE': timezone, 'RETURN_AS_TIMEZONE_AWARE': True, 'TO_TIMEZONE': 'UTC'}) + settings = {'TIMEZONE': timezone, 'RETURN_AS_TIMEZONE_AWARE': True, 'TO_TIMEZONE': 'UTC'} + + if prefer_past: + settings['PREFER_DATES_FROM'] = 'past' + + dt = dateparser.parse(string, settings=settings) if dt is None: raise ValueError('invalid datetime input specified.') diff --git a/tests/test_maya.py b/tests/test_maya.py index a28a54a..4b5fce8 100644 --- a/tests/test_maya.py +++ b/tests/test_maya.py @@ -170,6 +170,17 @@ def test_parse(): d = maya.parse('01/05/2016', day_first=True) assert format(d) == '2016-05-01 00:00:00+00:00' +def test_when_past(): + next_month = str(maya.now().add(months=1).month) + this_year = maya.now().year + last_year = this_year - 1 + + future_date = maya.when(next_month) + past_date = maya.when(next_month, prefer_past=True) + + assert future_date.year == this_year + assert past_date.year == last_year + def test_datetime_to_timezone(): dt = maya.when('2016-01-01').datetime(to_timezone='US/Eastern')