自动查找未来日期:
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
注意:“29 feb”翻译为“2016-02-29”。