TheMarlinCode
TheMarlinCode

Reputation: 33

Parsing string into datetime in Python

I have a date with this format

October 14, 2014 1:35PM PDT

I have this in my python script

import time

u_date = 'October 14, 2014 1:35PM PDT'

print  time.strptime(u_date,"%b %d, %y %I:%M%p %Z")

I got this error as a result

ValueError: time data u'October 14, 2014 1:35PM PDT' does not match format '%b %d, %y %I:%M%p %Z'

Can anyone explain to me why is this happening? I'm new to python and any help will be appreciated.

Upvotes: 0

Views: 140

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121406

Your format is incorrect; %b takes an abbreviated month, but you have a full month, requiring %B, and you have a full 4-digit year, so use %Y, not %y.

The time library cannot parse timezones, however, you'll have to drop the %Z part here and remove the last characters for this to work at all:

>>> time.strptime(u_date[:-4], "%B %d, %Y %I:%M%p")
time.struct_time(tm_year=2014, tm_mon=10, tm_mday=14, tm_hour=13, tm_min=35, tm_sec=0, tm_wday=1, tm_yday=287, tm_isdst=-1)

You could use the dateutil library instead to parse the full string, it'll produce a datetime.datetime object rather than a time struct:

>>> from dateutil import parser
>>> parser.parse(u_date)
datetime.datetime(2014, 10, 14, 13, 35)

Upvotes: 2

Related Questions