You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.10.8中datetime.fromisoformat文档示例报错问题咨询

问题解答

这既不是Python的Bug,也不是文档错误,而是版本兼容性问题。

  • datetime.fromisoformat() 对带Z后缀的UTC时间字符串的支持,是在Python 3.11版本才新增的功能。
  • 你使用的Python 3.10.8属于3.10系列,该版本的fromisoformat()仅支持不带时区后缀,或带+HH:MM/-HH:MM格式时区偏移的ISO字符串,无法识别Z(代表UTC)。

版本行为验证

在Python 3.10.x中执行以下代码:

from datetime import datetime
print(datetime.fromisoformat('2011-11-04T00:05:23Z'))

确实会抛出错误:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(datetime.fromisoformat('2011-11-04T00:05:23Z'))
ValueError: Invalid isoformat string: '2011-11-04T00:05:23Z'

这是3.10版本的预期行为。

而官方文档展示的示例,对应的是Python 3.11及以上版本的特性。3.11版本开始,fromisoformat()正式支持解析带Z后缀的UTC时间字符串,返回结果如下:

>>> datetime.fromisoformat('2011-11-04T00:05:23Z')
datetime.datetime(2011, 11, 4, 0, 5, 23, tzinfo=datetime.timezone.utc)

3.10.x版本的替代方案

如果需要在Python 3.10及以下版本解析带Z的ISO字符串,可以手动将Z替换为+00:00:

from datetime import datetime

iso_str = '2011-11-04T00:05:23Z'
adjusted_str = iso_str.replace('Z', '+00:00')
dt = datetime.fromisoformat(adjusted_str)
print(dt)  # 输出:2011-11-04 00:05:23+00:00

内容的提问来源于stack exchange,提问作者Marco Ocram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:33:13