← 中文资源

简体中文版本

datetime 与 ISO 8601 字符串往返

isoformat 渲染带时区的 datetime,fromisoformat 无损还原;3.11 起还接受 Web 风格的 Z 后缀与显式偏移,跨系统传日期不再手写解析。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

iso : 2026-11-18T09:30:00+00:00
round trip equal: True
zulu: UTC 0:00:00
shifted offset: 8:00:00
as utc: 2026-11-18T09:30:00+00:00

实现说明

各个操作都建立在顶层绑定之上:moment、text、zulu、shifted。

使用要点

  • 演示输出是带标签的(iso :、round trip equal:、zulu:),每个操作都会留下自己的一行标注。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 状态都挂在模块顶层:moment、text、zulu。

代码示例

from datetime import datetime, timezone

# isoformat() renders a datetime; fromisoformat() parses it back losslessly.
moment = datetime(2026, 11, 18, 9, 30, 0, tzinfo=timezone.utc)
text = moment.isoformat()
print("iso :", text)
print("round trip equal:", datetime.fromisoformat(text) == moment)

# Python 3.11+ also accepts the web-style 'Z' suffix for UTC.
zulu = datetime.fromisoformat("2026-11-18T09:30:00Z")
print("zulu:", zulu.tzinfo, zulu.utcoffset())

# Offsets ride along through parsing and conversion.
shifted = datetime.fromisoformat("2026-11-18T17:30:00+08:00")
print("shifted offset:", shifted.utcoffset())
print("as utc:", shifted.astimezone(timezone.utc).isoformat())