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

求助:使用datetime.strptime解析含.746Z的DateTime字符串遇问题

解决datetime.strptime处理带.Z后缀时间字符串的问题

你的代码出错原因有两个:

  • .746是毫秒(微秒片段),需要用%f匹配,而非%z
  • 末尾的Z是UTC时区标识,%z仅支持±HHMM/±HH:MM格式的偏移,无法直接匹配Z

下面是几种可行的解决方案:

方案1:替换Z为UTC偏移后用%z匹配

from datetime import datetime

datetime_str = '2022-04-21T08:17:49.746Z'
# 将Z替换为UTC标准时区偏移+0000
adjusted_str = datetime_str.replace('Z', '+0000')
datetime_object = datetime.strptime(adjusted_str, '%Y-%m-%dT%H:%M:%S.%f%z')
print(datetime_object)

方案2:格式字符串直接匹配Z,再手动设置时区

from datetime import datetime, timezone

datetime_str = '2022-04-21T08:17:49.746Z'
# 用%f匹配毫秒,格式末尾写Z匹配字符
datetime_object = datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S.%fZ')
# 手动将时区设置为UTC
datetime_object = datetime_object.replace(tzinfo=timezone.utc)
print(datetime_object)

方案3:用fromisoformat简化处理(Python 3.10+)

from datetime import datetime

datetime_str = '2022-04-21T08:17:49.746Z'
# Python 3.10需要替换Z为+00:00,3.11+可直接传入原字符串
datetime_object = datetime.fromisoformat(datetime_str.replace('Z', '+00:00'))
print(datetime_object)

内容的提问来源于stack exchange,提问作者Clay Campbell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:50:20