Question

I am need to convert a date in below format into different format for displaying purpose. But before that I am trying to convert the date in string to time object, but not able to do so.

>>> time.strptime("Thu Mar 13 23:15:13 2014 EDT", '%a %b %d %H:%M:%S %Y %Z')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib64/python2.4/_strptime.py", line 293, in strptime
    raise ValueError("time data did not match format:  data=%s  fmt=%s" %
ValueError: time data did not match format:  data=Thu Mar 13 23:15:13 2014 EDT  fmt=%a %b %d %H:%M:%S %Y %Z

Did a trial and error and it's the '%Z' causing the issue, below works fine (just %Z is removed)

>>> time.strptime("Thu Mar 13 23:15:13 2014", '%a %b %d %H:%M:%S %Y')
(2014, 3, 13, 23, 15, 13, 3, 72, -1)

Python wiki (https://docs.python.org/2/library/time.html) says timezone specifier is %Z, then what is the issue here. Please help me find.

Python version: 2.4.3

Was it helpful?

Solution

From the Python documentation. https://docs.python.org/2/library/time.html#time.strptime

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

Which basically says that time.strptime() will only recognize timezones that are listed in time.tzname

Hope this helps

OTHER TIPS

%z will only work for numeric timezone in python 3.x, here is a fix for python 2.x:

Instead of using:

datetime.strptime(t,'%Y-%m-%dT%H:%M %z')

use the timedelta to account for the timezone, like this:

from datetime import datetime,timedelta
def dt_parse(t):
    ret = datetime.strptime(t[0:16],'%Y-%m-%dT%H:%M')
    if t[18]=='+':
        ret+=timedelta(hours=int(t[19:22]),minutes=int(t[23:]))
    elif t[18]=='-':
        ret-=timedelta(hours=int(t[19:22]),minutes=int(t[23:]))
    return ret
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top