jim jarnac
jim jarnac

Reputation: 5152

Parsing datestring in Python

I have the following datestring:

d = 'Fri Nov 20, 7:54AM CST'

That i am trying to parse using the following code:

from datetime import datetime as dt
dt.strptime(d, '%a %b %d, %I:%M%p %Z')

I receive the following error: ValueError: time data 'Fri Nov 20, 7:54AM CST' does not match format '%a %b %d, %I:%M%p %Z'

I don't understand what i am doing wrong, can anyone help ?

Upvotes: 2

Views: 98

Answers (1)

butterflyknife
butterflyknife

Reputation: 1574

Does this help? It's a bit unclear what you want to do with the timezone, so I've shown two options (ignore or not).

from dateutil.parser import parse
from dateutil.tz import gettz

d = 'Fri Nov 19, 7:54AM CST'

print(parse(d)) // 2020-11-19 07:54:00

tzinfos = {"CST": gettz("America/Chicago")}
print(parse(d, tzinfos=tzinfos)) // 2020-11-19 07:54:00-06:00

Also you haven't specified how you want to set the year; the default is to use the current year (I changed your example to the 19th of November to make this clear).

EDIT: to answer your actual question, your code doesn't work because (a) %I expects a zero-padded decimal number (actually, see Edit 2), and (b) %Z only accepts empty, 'UTC' or 'GMT'.

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

EDIT 2: Digging a bit deeper, the following works (changed CST to GMT to make it work):

d = 'Fri Nov 19, 7:54AM GMT'
print(dt.strptime(d, '%a %b %d, %I:%M%p %Z')) // 1900-11-19 07:54:00
                                              // Note the year is now 1900.

So it appears that '%I' doesn't in fact require a zero-padded number, in contradiction to the linked page above. Don't know what's going on there.

Upvotes: 3

Related Questions