[英]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: 我正在尝试将以下字符串解析为有效的datetime格式:
Wed, 10 Sep 2014 11:20:58 +0000
for which I use this Python code: 为此,我使用以下Python代码:
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
. 根据strptime()文档 ,对于UTC offset in the form +HHMM or -HHMM
, %z
应该完全正确, 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) 看起来strptime
并不总是支持%z
(请参阅此答案)
Instead of strptime
, you can use dateutil.parser
and it works fine: 可以使用dateutil.parser
代替strptime
,它可以正常工作:
>>> 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.