0

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.

6
  • %Z can only format timezones, not parse them. Commented Aug 9, 2015 at 2:14
  • Plus, you need %B for a full month name and %Y for a 4-digit year. Commented Aug 9, 2015 at 2:15
  • See this topic which is basically trying to do the same thing you are: stackoverflow.com/questions/10494312/… Commented Aug 9, 2015 at 2:19
  • This question seems relevant: stackoverflow.com/questions/1703546/… Commented Aug 9, 2015 at 2:19
  • Martijn Pieters' answer below should help. For more info on format codes, see here - I thought it was very helpful: docs.python.org/2/library/… Commented Aug 9, 2015 at 2:26

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

time.strptime('October 14, 2014 1:35PM PDT', "%B %d, %Y %I:%M%p %Z") works if your local timezone is America/Los_Angeles. Otherwise timezone abbreviations such as PDT may be ambiguous and parser.parse() may return a wrong result (wrong zone name, wrong utc offset).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.