简体   繁体   中英

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM