Default “future” year when effecting date conversion with dateutil

懵懂的女人 提交于 2019-12-25 11:50:53

问题


The following date patterns

1st January
30th April

are easily parsed into instances of datetime.date via dateutil.parser.parse():

In [1]:from dateutil.parser import parse

In [2]: parse('1st January')
Out[2]: datetime.datetime(2012, 1, 1, 0, 0)

In [3]: parse('8th April')
Out[3]: datetime.datetime(2012, 4, 30, 0, 0)

How can a future date be returned from parsing?

I.e. parsing '1st January' would return datetime.datetime(2013, 1, 1, 0, 0), 1st January 2013 and not 1st January 2012. Any elegant solution?


回答1:


Starting with mensi's excellent answer to your previous question, here's a solution that takes dates without a specified year and makes sure they're not in the past. If the year is given as part of the string it is kept intact.

import datetime
import dateutil

def parse(date_string):
    result = dateutil.parser.parse(date_string, default=datetime.datetime(1581, 1, 1))
    if result.year == 1581:
        now = datetime.datetime.now()
        result = result.replace(year=now.year)
        if result < now:
            result = result.replace(year=now.year + 1)
    return result

parse('8th April')


来源:https://stackoverflow.com/questions/10130091/default-future-year-when-effecting-date-conversion-with-dateutil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!