Search code examples
pythondatetimepython-dateutil

day is out of range for month: February 29,2016 dateutil - Leap year issue


Code:

from dateutil.parser import parse
dates = parse('February 29,2016').strftime("%Y-%m-%d")
print(dates)

Error:

''' day is out of range for month: February 29,2016 '''

It seems like leap year is not considered here. Can anyone help me detect 29 February 2016 in the format of 2016-02-29

library versions: python-dateutil - 2.8.2


Solution

  • It's probably not a supported date format. If you change it to the 28th, you'll notice the year it captures is the current year, not 2016, hence the error.

    parse('February 28,2016')
    

    Output

    datetime.datetime(2021, 2, 28, 0, 0)
    

    If you add a space after the comma, it becomes a supported format and successfully parses.

    parse('February 29, 2016')
    

    Output

    datetime.datetime(2016, 2, 29, 0, 0)