实现说明
各个操作都建立在顶层绑定之上: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())