也许使用.isoformat()
ISO 8601 格式的字符串,YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM]
>>> import datetime
>>> datetime.datetime.utcnow().isoformat() + "Z"
'2013-07-11T22:26:51.564000Z'
>>>
Z 指定“zulu”时间或 UTC。
您还可以通过应用适当的 tzinfo 对象使您的日期时间对象时区感知来添加时区组件。应用 tzinfo 后,.isoformat() 方法将在输出中包含适当的 utc 偏移量:
>>> d = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
>>> d.isoformat()
'2019-11-11T00:52:43.349356+00:00'
您可以通过将 microseconds 值更改为 0 来删除 microseconds:
>>> no_ms = d.replace(microsecond=0)
>>> no_ms.isoformat()
'2019-11-11T00:52:43+00:00'
此外,从 python 3.7 开始,.fromisoformat() 方法可用于将 iso 格式的日期时间字符串加载到 python 日期时间对象中:
>>> datetime.datetime.fromisoformat('2019-11-11T00:52:43+00:00')
datetime.datetime(2019, 11, 11, 0, 52, 43, tzinfo=datetime.timezone.utc)
http://www.ietf.org/rfc/rfc3339.txt