编程语言
首页 > 编程语言> > Python智能日期解析没有指定年份

Python智能日期解析没有指定年份

作者:互联网

如何解析日期(使用dateutil)而不是一年,这样当当前日期是17/11/2012时,这些日期将被解析为:

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

我想要的是已经过去的几个月将是今年之后的一年.这有什么简单的解决方案吗?

解决方法:

要自动查找未来日期:

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”.

标签:python,python-dateutil
来源: https://codeday.me/bug/20190625/1287385.html