I am using dateutils.parser.parse
to parse date strings which might contain partial information. If some information is not present, parse
can take a default
keyword argument from which it will fill any missing fields. This default defaults to datetime.datetime.today()
.
For a case like dateutil.parser.parse("Thursday")
, this means it will return the date of the next Thursday. However, I need it to return the date of the last Thursday (including today, if today happens to be a Thursday).
So, assuming today == datetime.datetime(2018, 2, 20)
(a Tuesday), I would like to get all of these assert
s to be true:
from dateutil import parser
from datetime import datetime
def parse(date_str, default=None):
# this needs to be modified
return parser.parse(date_str, default=default)
today = datetime(2018, 2, 20)
assert parse("Tuesday", default=today) == today # True
assert parse("Thursday", default=today) == datetime(2018, 2, 15) # False
assert parse("Jan 31", default=today) == datetime(2018, 1, 31) # True
assert parse("December 10", default=today) == datetime(2017, 12, 10) # False
Is there an easy way to achieve this? With the current parse
function only the first and third assert
would pass.