为什么 datetime.now().isoformat() return 根据 time.fromisoformat() 是无效的同种格式字符串?
Why does datetime.now().isoformat() return an invalid isoformat string according to time.fromisoformat()?
运行 Python 3.8.10,今天遇到这个:
from datetime import datetime, time
time.fromisoformat(datetime.now().isoformat())
结果:
Traceback (most recent call last):
ValueError: Invalid isoformat string: '2021-09-02T17:16:49.330690'
为什么 datetime.datetime 模块创建的同格式字符串被 datetime.time 模块视为无效?
您正在使用 time.fromisoformat
, which only handles time strings. To parse a full datetime, use datetime.fromisoformat
:
>>> from datetime import datetime, time
# Bad
>>> time.fromisoformat(datetime.now().isoformat())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Invalid isoformat string: '2021-09-02T17:31:25.857666'
# Good
>>> datetime.fromisoformat(datetime.now().isoformat())
datetime.datetime(2021, 9, 2, 17, 31, 43, 685120)
因为 datetime.now
给你 日期 和 时间 ,而 time.fromisoformat
想要 time 仅字符串。
来自 time.fromisoformat
文档:
Caution
This does not support parsing arbitrary ISO 8601 strings. It is only intended as the inverse operation of time.isoformat()
.
再试一次
datetime.now().time()
代替。
运行 Python 3.8.10,今天遇到这个:
from datetime import datetime, time
time.fromisoformat(datetime.now().isoformat())
结果:
Traceback (most recent call last): ValueError: Invalid isoformat string: '2021-09-02T17:16:49.330690'
为什么 datetime.datetime 模块创建的同格式字符串被 datetime.time 模块视为无效?
您正在使用 time.fromisoformat
, which only handles time strings. To parse a full datetime, use datetime.fromisoformat
:
>>> from datetime import datetime, time
# Bad
>>> time.fromisoformat(datetime.now().isoformat())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Invalid isoformat string: '2021-09-02T17:31:25.857666'
# Good
>>> datetime.fromisoformat(datetime.now().isoformat())
datetime.datetime(2021, 9, 2, 17, 31, 43, 685120)
因为 datetime.now
给你 日期 和 时间 ,而 time.fromisoformat
想要 time 仅字符串。
来自 time.fromisoformat
文档:
Caution
This does not support parsing arbitrary ISO 8601 strings. It is only intended as the inverse operation of
time.isoformat()
.
再试一次
datetime.now().time()
代替。