如何将 Python 的 .isoformat() 字符串转换回日期时间对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28331512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Python's .isoformat() string back into datetime object
提问by Alex Urcioli
So in Python 3, you can generate an ISO 8601 date with .isoformat(), but you can't convert a string created by isoformat() back into a datetime object because Python's own datetime directives don't match properly. That is, %z = 0500 instead of 05:00 (which is produced by .isoformat()).
因此,在 Python 3 中,您可以使用 .isoformat() 生成 ISO 8601 日期,但您无法将 isoformat() 创建的字符串转换回日期时间对象,因为 Python 自己的日期时间指令不正确匹配。也就是说,%z = 0500 而不是 05:00(由 .isoformat() 生成)。
For example:
例如:
>>> strDate = d.isoformat()
>>> strDate
'2015-02-04T20:55:08.914461+00:00'
>>> objDate = datetime.strptime(strDate,"%Y-%m-%dT%H:%M:%S.%f%z")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\Lib\_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Python34\Lib\_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '2015-02-04T20:55:08.914461+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
From Python's strptime documentation: (https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior)
来自 Python 的 strptime 文档:(https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior)
%z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive). (empty), +0000, -0400, +1030
%z UTC 偏移量,格式为 +HHMM 或 -HHMM(如果对象是幼稚的,则为空字符串)。(空)、+0000、-0400、+1030
So, in short, Python does not even adhere to its own string formatting directives.
因此,简而言之,Python 甚至不遵守自己的字符串格式指令。
I know datetime is already terrible in Python, but this really goes beyond unreasonable into the land of plain stupidity.
我知道 Python 中的 datetime 已经很糟糕了,但这确实超出了不合理的范围,进入了愚蠢的领域。
Tell me this isn't true.
告诉我这不是真的。
采纳答案by Alex Urcioli
As it turns out, this is the current best "solution" to this question:
事实证明,这是这个问题目前最好的“解决方案”:
pip install python-dateutil
Then...
然后...
import datetime
import dateutil.parser
def getDateTimeFromISO8601String(s):
d = dateutil.parser.parse(s)
return d
回答by user 12321
Try this:
尝试这个:
>>> def gt(dt_str):
... dt, _, us = dt_str.partition(".")
... dt = datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
... us = int(us.rstrip("Z"), 10)
... return dt + datetime.timedelta(microseconds=us)
Usage:
用法:
>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)