Python UTC datetime object#39;s ISO format doesn#39;t include Z (Zulu or Zero offset)(Python UTC 日期时间对象的 ISO 格式不包括 Z(祖鲁语或零偏移))
问题描述
为什么 python 2.7 不像 JavaScript 那样在 UTC 日期时间对象的 isoformat 字符串的末尾不包含 Z 字符(Zulu 或零偏移)?
Why python 2.7 doesn't include Z character (Zulu or zero offset) at the end of UTC datetime object's isoformat string unlike JavaScript?
>>> datetime.datetime.utcnow().isoformat()
'2013-10-29T09:14:03.895210'
而在 javascript 中
Whereas in javascript
>>> console.log(new Date().toISOString());
2013-10-29T09:38:41.341Z
推荐答案
Python datetime
对象默认没有时区信息,没有它,Python 实际上违反了 ISO 8601 规范(如果没有给出时区信息,则假定为当地时间).您可以使用 pytz 包 来获取一些默认时区,或者直接子类化 tzinfo
你自己:
Python datetime
objects don't have time zone info by default, and without it, Python actually violates the ISO 8601 specification (if no time zone info is given, assumed to be local time). You can use the pytz package to get some default time zones, or directly subclass tzinfo
yourself:
from datetime import datetime, tzinfo, timedelta
class simple_utc(tzinfo):
def tzname(self,**kwargs):
return "UTC"
def utcoffset(self, dt):
return timedelta(0)
然后你可以手动将时区信息添加到utcnow()
:
Then you can manually add the time zone info to utcnow()
:
>>> datetime.utcnow().replace(tzinfo=simple_utc()).isoformat()
'2014-05-16T22:51:53.015001+00:00'
请注意,这符合 ISO 8601 格式,该格式允许 Z
或 +00:00
作为 UTC 的后缀.请注意,后者实际上更符合标准,通常表示时区(UTC 是一个特例.)
Note that this DOES conform to the ISO 8601 format, which allows for either Z
or +00:00
as the suffix for UTC. Note that the latter actually conforms to the standard better, with how time zones are represented in general (UTC is a special case.)
这篇关于Python UTC 日期时间对象的 ISO 格式不包括 Z(祖鲁语或零偏移)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python UTC 日期时间对象的 ISO 格式不包括 Z(祖鲁语或零偏移)


基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01