問(wèn)題描述
為什么 python 2.7 不像 JavaScript 那樣在 UTC 日期時(shí)間對(duì)象的 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
對(duì)象默認(rèn)沒(méi)有時(shí)區(qū)信息,沒(méi)有它,Python 實(shí)際上違反了 ISO 8601 規(guī)范(如果沒(méi)有給出時(shí)區(qū)信息,則假定為當(dāng)?shù)貢r(shí)間).您可以使用 pytz 包 來(lái)獲取一些默認(rèn)時(shí)區(qū),或者直接子類(lèi)化 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)
然后你可以手動(dòng)將時(shí)區(qū)信息添加到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'
請(qǐng)注意,這符合 ISO 8601 格式,該格式允許 Z
或 +00:00
作為 UTC 的后綴.請(qǐng)注意,后者實(shí)際上更符合標(biāo)準(zhǔn),通常表示時(shí)區(qū)(UTC 是一個(gè)特例.)
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.)
這篇關(guān)于Python UTC 日期時(shí)間對(duì)象的 ISO 格式不包括 Z(祖魯語(yǔ)或零偏移)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!