Python UTC 日期时间对象的 ISO 格式不包括 Z(祖鲁语或零偏移量)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19654578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)
提问by Murali Mopuru
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?
与 JavaScript 不同,为什么 python 2.7 在 UTC datetime 对象的 isoformat 字符串末尾不包含 Z 字符(Zulu 或零偏移量)?
>>> datetime.datetime.utcnow().isoformat()
'2013-10-29T09:14:03.895210'
Whereas in javascript
而在 javascript 中
>>> console.log(new Date().toISOString());
2013-10-29T09:38:41.341Z
采纳答案by stiv
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 packageto get some default time zones, or directly subclass tzinfo
yourself:
Pythondatetime
对象默认没有时区信息,没有它,Python 实际上违反了 ISO 8601 规范(如果没有给出时区信息,则假定为本地时间)。你可以使用pytz 包来获取一些默认时区,或者直接tzinfo
自己子类化:
from datetime import datetime, tzinfo, timedelta
class simple_utc(tzinfo):
def tzname(self,**kwargs):
return "UTC"
def utcoffset(self, dt):
return timedelta(0)
Then you can manually add the time zone info to utcnow()
:
然后您可以手动将时区信息添加到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.)
请注意,这确实符合 ISO 8601 格式,该格式允许使用UTCZ
或+00:00
作为 UTC 的后缀。请注意,后者实际上更符合标准,时区通常是如何表示的(UTC 是一个特例。)
回答by U2EF1
Python datetimes are a little clunky. Use arrow
.
Python 日期时间有点笨拙。使用arrow
.
> str(arrow.utcnow())
'2014-05-17T01:18:47.944126+00:00'
Arrow has essentially the same api as datetime, but with timezones and some extra niceties that should be in the main library.
Arrow 具有与 datetime 基本相同的 api,但具有时区和一些应该在主库中的额外细节。
A format compatible with Javascript can be achieved by:
可以通过以下方式实现与 Javascript 兼容的格式:
arrow.utcnow().isoformat().replace("+00:00", "Z")
'2018-11-30T02:46:40.714281Z'
Javascript Date.parse
will quietly drop microseconds from the timestamp.
JavascriptDate.parse
会悄悄地从时间戳中删除微秒。
回答by Manav Kataria
Option: isoformat()
选项: isoformat()
Python's datetime
does not support the military timezonesuffixes like 'Z' suffix for UTC. The following simple string replacement does the trick:
Pythondatetime
不支持军用时区后缀,例如 UTC 的“Z”后缀。以下简单的字符串替换可以解决问题:
In [1]: import datetime
In [2]: d = datetime.datetime(2014, 12, 10, 12, 0, 0)
In [3]: str(d).replace('+00:00', 'Z')
Out[3]: '2014-12-10 12:00:00Z'
str(d)
is essentially the same as d.isoformat(sep=' ')
str(d)
本质上是一样的 d.isoformat(sep=' ')
See: Datetime, Python Standard Library
请参阅:日期时间,Python 标准库
Option: strftime()
选项: strftime()
Or you could use strftime
to achieve the same effect:
或者你可以用它strftime
来达到同样的效果:
In [4]: d.strftime('%Y-%m-%d %H:%M:%SZ')
Out[4]: '2014-12-10 12:00:00Z'
Note: This option works only when you know the date specified is in UTC.
注意:只有当您知道指定的日期是 UTC 时,此选项才有效。
See: datetime.strftime()
Additional: Human Readable Timezone
附加:人类可读时区
Going further, you may be interested in displaying human readable timezone information, pytz
with strftime
%Z
timezone flag:
进一步说,你可能有兴趣在显示人类可读的时区信息,pytz
与strftime
%Z
时区标志:
In [5]: import pytz
In [6]: d = datetime.datetime(2014, 12, 10, 12, 0, 0, tzinfo=pytz.utc)
In [7]: d
Out[7]: datetime.datetime(2014, 12, 10, 12, 0, tzinfo=<UTC>)
In [8]: d.strftime('%Y-%m-%d %H:%M:%S %Z')
Out[8]: '2014-12-10 12:00:00 UTC'
回答by EmptyData
By combining all answers above I came with following function :
通过结合上面的所有答案,我得到了以下功能:
from datetime import datetime, tzinfo, timedelta
class simple_utc(tzinfo):
def tzname(self,**kwargs):
return "UTC"
def utcoffset(self, dt):
return timedelta(0)
def getdata(yy, mm, dd, h, m, s) :
d = datetime(yy, mm, dd, h, m, s)
d = d.replace(tzinfo=simple_utc()).isoformat()
d = str(d).replace('+00:00', 'Z')
return d
print getdata(2018, 02, 03, 15, 0, 14)
回答by Michael Cox
There are a lot of good answers on the post, but I wanted the format to come out exactly as it does with JavaScript. This is what I'm using and it works well.
帖子中有很多很好的答案,但我希望格式与 JavaScript 完全一样。这就是我正在使用的,并且效果很好。
In [1]: import datetime
In [1]: now = datetime.datetime.utcnow()
In [1]: now.strftime('%Y-%m-%dT%H:%M:%S') + now.strftime('.%f')[:4] + 'Z'
Out[3]: '2018-10-16T13:18:34.856Z'
回答by digitalshadow
>>> import arrow
>>> now = arrow.utcnow().format('YYYY-MM-DDTHH:mm:ss.SSS')
>>> now
'2018-11-28T21:34:59.235'
>>> zulu = "{}Z".format(now)
>>> zulu
'2018-11-28T21:34:59.235Z'
Or, to get it in one fell swoop:
或者,一举搞定:
>>> zulu = "{}Z".format(arrow.utcnow().format('YYYY-MM-DDTHH:mm:ss.SSS'))
>>> zulu
'2018-11-28T21:54:49.639Z'
回答by Jam Risser
The following javascript and python scripts give identical outputs. I think it's what you are looking for.
以下 javascript 和 python 脚本给出相同的输出。我想这就是你要找的。
JavaScript
JavaScript
new Date().toISOString()
Python
Python
import datetime
datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
The output they give is the utc (zelda) time formatted as an ISO string with a 3 millisecond significant digit and appended with a Z.
他们给出的输出是格式化为 ISO 字符串的 utc (zelda) 时间,带有 3 毫秒有效数字并附加一个 Z。
2019-01-19T23:20:25.459Z
回答by Michel Samia
In Python >= 3.2 you can simply use this:
在 Python >= 3.2 中,你可以简单地使用这个:
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2019-03-14T07:55:36.979511+00:00'
回答by W Yg
pip install python-dateutil
>>> a = "2019-06-27T02:14:49.443814497Z"
>>> dateutil.parser.parse(a)
datetime.datetime(2019, 6, 27, 2, 14, 49, 443814, tzinfo=tzutc())
回答by user3249641
I use pendulum:
我使用钟摆:
import pendulum
d = pendulum.now("UTC").to_iso8601_string()
print(d)
>>> 2019-10-30T00:11:21.818265Z