ste*_*lff 17 python iso8601 python-3.x python-3.7
我提供"2019-04-05T16:55:26Z"给 Python 3datetime.datetime.fromisoformat和 get Invalid isoformat string,尽管相同的字符串在没有 Z 的情况下也能工作。 ISO8601 允许 Z - https://en.wikipedia.org/wiki/ISO_8601
$ python3
Python 3.7.2 (default, Feb 12 2019, 08:15:36)
>>> datetime.fromisoformat("2019-04-05T16:55:26Z")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Invalid isoformat string: '2019-04-05T16:55:26Z'
>>> datetime.fromisoformat("2019-04-05T16:55:26")
datetime.datetime(2019, 4, 5, 16, 55, 26)
Run Code Online (Sandbox Code Playgroud)
Nic*_*ood 30
如果您已经知道 API 响应的格式,您可以使用:
from datetime import datetime
datetime.strptime("2022-04-07T08:53:42.06717+02:00", "%Y-%m-%dT%H:%M:%S.%f%z")
Run Code Online (Sandbox Code Playgroud)
根据您的需要进行调整,例如,如果字符串不包含毫秒等。
否则,正如官方 python 文档所建议的那样,请使用该dateutil包: https: //dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse
小智 17
3.11 现在支持正确的 ISO 格式,包括时区
https://docs.python.org/3.11/library/datetime.html#datetime.datetime.fromisoformat
ste*_*lff 10
我刚刚检查了 Python 3 文档,它并不打算解析任意的 ISO8601 格式字符串:
注意:这不支持解析任意 ISO 8601 字符串 - 它仅用作
datetime.isoformat().