Default “future” year when effecting date conversi

2019-08-22 16:57发布

问题:

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')