Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Smart date parsing without a year specified

How can I parse dates (with dateutil) without a year so that when the current date is 17/11/2012 these dates will be parsed like this:

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

What I want is that already passed months will be in the year that follows the current year. Is there any easy solution for this?

like image 929
Dieter Avatar asked Oct 06 '22 23:10

Dieter


1 Answers

To find future dates automatically:

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

Example

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

Output

2012-11-23
2012-12-28
2013-01-03
2016-02-29

Note: "29 feb" is translated to "2016-02-29".

like image 158
jfs Avatar answered Oct 10 '22 02:10

jfs