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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
TheMarlinCode
  • 33
  • 1
  • 7
  • `%Z` can only format timezones, not parse them. – Martijn Pieters Aug 09 '15 at 02:14
  • Plus, you need `%B` for a full month name and `%Y` for a 4-digit year. – alecxe Aug 09 '15 at 02:15
  • See this topic which is basically trying to do the same thing you are: http://stackoverflow.com/questions/10494312/parsing-time-string-in-python – NJM Aug 09 '15 at 02:19
  • This question seems relevant: https://stackoverflow.com/questions/1703546/parsing-date-time-string-with-timezone-abbreviated-name-in-python – Cyphase Aug 09 '15 at 02:19
  • Martijn Pieters' answer below should help. For more info on format codes, see here - I thought it was very helpful: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior – killthrush Aug 09 '15 at 02:26
  • @NJM: parsing a time string with a numeric utc offset (`%z`) is different from a string with timezone abbreviation (`%Z`). The latter may be ambiguous. – jfs Aug 09 '15 at 15:07

1 Answers1

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • `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). – jfs Aug 09 '15 at 14:46