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

时间:2012-11-17 10:04:03

标签: python python-dateutil

如何解析日期(使用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

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

2 个答案:

答案 0 :(得分:4)

自动查找未来日期:

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"。

答案 1 :(得分:0)

此功能在过去几个月的提供日期中添加一年:

from datetime import date
from dateutil.relativedelta import relativedelta

def add_one_year_to_passed_months(date):
    today = date.today()
    if date.month < today.month:
        return date + relativedelta(years=1)
    return date

2012年的闰年由relativedelta以这种方式处理:

>>> add_one_year_to_passed_months(date(2012, 2, 28))
datetime.date(2013, 2, 28)

>>> add_one_year_to_passed_months(date(2012, 2, 29))
datetime.date(2013, 2, 28)

>>> add_one_year_to_passed_months(date(2012, 3, 1))
datetime.date(2013, 3, 1)