Search code examples
pythonparsingdatetimestrptime

Why doesn't my Python code accept %z as a DateTime directive?


I'm trying to parse the following string into a valid datetime format:

Wed, 10 Sep 2014 11:20:58 +0000

for which I use this Python code:

dtObject = datetime.strptime(e[attr], '%a, %d %b %Y %H:%M:%S %z')

Unfortunately I get an error saying:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 317, in _str
ptime
    (bad_directive, format))
ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'

According to the strptime() docs, %z should be totally correct for UTC offset in the form +HHMM or -HHMM.

Does anybody know what I'm doing wrong here? All tips are welcome


Solution

  • It looks as if strptime doesn't always support %z (see this answer)
    Instead of strptime, you can use dateutil.parser and it works fine:

    >>> import dateutil.parser
    >>> s='Wed, 10 Sep 2014 11:20:58 +0000'  #UTC
    >>> dateutil.parser.parse(s)
    datetime.datetime(2014, 9, 10, 11, 20, 58, tzinfo=tzutc())
    
    
    >>> s='Wed, 10 Sep 2014 11:20:58 +0100'  #ANOTHER TZ
    >>> dateutil.parser.parse(s)
    datetime.datetime(2014, 9, 10, 11, 20, 58, tzinfo=tzoffset(None, 3600))