Skip to content Skip to sidebar Skip to footer

Python Parse Datestring To Date

I am trying to parse a datetime string to date in Python. The input value is of the form: 'February 19, 1989' I have been trying so far datetime.datetime.strptime('Feb

Solution 1:

The following works (changed small case y to uppercase Y):

datetime.datetime.strptime("February 19, 1989", "%B %d, %Y")

The reason is that %y is for 99, 98 and such, while %Y is for full year. You can read the full documentation on this here.

Solution 2:

In addition to David's answer, if you have a list of strings that have a variety of formats (say, some have two digit years and others have four), you can utilize the dateutil package to help parse these strings into datetime objects automagically.

from dateutil import parser

dates = ["February 19, 1989", "February 19, 89", "February 19, 01"]
for d in dates:
    print(parser.parse(d))

Prints three date time objects:

datetime.datetime(1989, 2, 19, 0, 0)
datetime.datetime(1989, 2, 19, 0, 0)
datetime.datetime(2001, 2, 19, 0, 0)

The downside to this, compared to the previously mentioned answer, is that it requires an extra package. The upside is that it is fairly good at determining your date without your needing to know the format string.

Post a Comment for "Python Parse Datestring To Date"