Python UTC日期时间对象的ISO格式不包含Z(Zulu或零偏移) [英] Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

查看:115
本文介绍了Python UTC日期时间对象的ISO格式不包含Z(Zulu或零偏移)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么python 2.7不像JavaScript那样在UTC日期时间对象的等格式字符串的末尾不包含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包来获取一些默认时区,或直接将<$ c $子类化c> 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(Zulu或零偏移)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆