How can I parse dates (with dateutil) without a year so that when the current date is 17/11/2012 these dates will be parsed like this:
print parser.parse("23 nov", dayfirst=True, yearfirst=False, fuzzy=True)
# 23/11/2012
print parser.parse("28 dec", dayfirst=True, yearfirst=False, fuzzy=True)
# 28/12/2012
print parser.parse("3 jan", dayfirst=True, yearfirst=False, fuzzy=True)
# 3/01/2013
What I want is that already passed months will be in the year that follows the current year. Is there any easy solution for this?
To find future dates automatically:
from dateutil import parser
from dateutil.relativedelta import relativedelta
def parse_future(timestr, default, **parse_kwargs):
"""Same as dateutil.parser.parse() but only returns future dates."""
now = default
for _ in range(401): # assume gregorian calendar repeats every 400 year
try:
dt = parser.parse(timestr, default=default, **parse_kwargs)
except ValueError:
pass
else:
if dt > now: # found future date
break
default += relativedelta(years=+1)
else: # future date not found
raise ValueError('failed to find future date for %r' % (timestr,))
return dt
from datetime import datetime
for timestr in ["23 nov", "28 dec", "3 jan", "29 feb"]:
print parse_future(timestr, default=datetime(2012, 11, 17)).date()
2012-11-23
2012-12-28
2013-01-03
2016-02-29
Note: "29 feb" is translated to "2016-02-29".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With