mirror of
https://github.com/kennethreitz/maya.git
synced 2026-06-05 06:46:14 +00:00
Add prefer_past option for when
When parsing dates from websites when encountering ambiguous dates like "December 12th" this is interpreted in the future (when the current date is in October). When parsing dates that we know must be in the past this is not the correct behavior. Add a `prefer_past` keyword argument to `when` to allow the user to ensure the date is parsed as being in the past.
This commit is contained in:
+8
-3
@@ -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.')
|
||||
|
||||
@@ -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_d.year == this_year
|
||||
assert past_d.year == last_year
|
||||
|
||||
|
||||
def test_datetime_to_timezone():
|
||||
dt = maya.when('2016-01-01').datetime(to_timezone='US/Eastern')
|
||||
|
||||
Reference in New Issue
Block a user