简体   繁体   English

为什么我的Python代码不接受%z作为DateTime指令?

[英]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.

相关问题 Python正则表达式:为什么python不接受我的模式? - Python Regex: why doesn't python accept my pattern? Hackerrank 不接受我的代码。 为什么? - Hackerrank doesn't accept my code. Why? 为什么我的网络抓取代码不接受 cookies - Why doesn't my webscrape code accept cookies Python 3.8.2 | 为什么我的输入不接受我的答案,即使它是有效的? (功能) - Python 3.8.2 | Why does my input doesn't accept my answer even if it's a valid one? (function) 为什么 python 不接受我从文本文件中获取的颜色? Python Tkinter - Why python doesn't accept my color i take from text file? Python Tkinter 知道为什么hackerrank 不接受我的代码,即使它准确打印了要求的内容 - Any idea why hackerrank doesn't accept my code even if it prints exactly what is asked python:%z 指令的 datetime.datetime.strptime 错误 - python: datetime.datetime.strptime error with %z directive 为什么SQLITE使用Python 3不接受大于8的My INTEGER / TEXT数据? - Why SQLITE doesn't accept My INTEGER/TEXT data larger than 8, using Python 3? 为什么条件“ else”在我的python代码中不起作用 - Why condition “else” doesn't work in my python code 为什么这个 Python 熊猫代码不能在我的数据集上运行? - Why doesn't this Python pandas code work on my dataset?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM