Python UTC datetime对象的ISO格式不包括Z(Zulu或Zero offset) [英] Python UTC datetime object's ISO format dont include Z (Zulu or Zero offset)
问题描述
>>> datetime.datetime.utcnow()。isoformat()
'2013-10-29T09:14:03.895210'
而在javascript中
>>> console.log(new Date()。toISOString());
2013-10-29T09:38:41.341Z
Python datetime
对象默认情况下没有时区信息,没有它,Python实际上违反了ISO 8601规范(如果没有给定时区信息,假定是本地时间)。您可以使用 pytz包获取一些默认时区,或直接子类 tzinfo
你自己:
从$ datetime import datetime,tzinfo,timedelta
class simple_utc(tzinfo):
def tzname(self):
returnUTC
def utcoffset(self,dt):
return timedelta(0)
/ pre>
然后您可以手动将时区信息添加到
utcnow()
:>>> datetime.utcnow()。replace(tzinfo = simple_utc())。isoformat()
pre>
'2014-05-16T22:51:53.015001 + 00:00'
请注意,此DOES符合ISO 8601格式,允许
Z
或+00:00
作为UTC的后缀。请注意,后者实际上更符合标准,通常时区如何表示(UTC是一种特殊情况。)Anybody knows why python 2.7 don'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'
Whereas in javascript
>>> console.log(new Date().toISOString()); 2013-10-29T09:38:41.341Z
解决方案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 subclasstzinfo
yourself:from datetime import datetime, tzinfo, timedelta class simple_utc(tzinfo): def tzname(self): return "UTC" def utcoffset(self, dt): return timedelta(0)
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'
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 datetime对象的ISO格式不包括Z(Zulu或Zero offset)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!