为什么python 2.7不包括Z字符(Zulu或零偏移量)在UTC datetime对象的isoformat字符串结束不像JavaScript?

>>> datetime.datetime.utcnow().isoformat()
'2013-10-29T09:14:03.895210'

而在javascript中

>>>  console.log(new Date().toISOString()); 
2013-10-29T09:38:41.341Z

当前回答

在Python >= 3.2中,你可以简单地使用:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2019-03-14T07:55:36.979511+00:00'

其他回答

Python日期时间有点笨拙。使用箭头。

> str(arrow.utcnow())
'2014-05-17T01:18:47.944126+00:00'

Arrow拥有本质上与datetime相同的api,但带有时区和一些额外的细节,这些应该在主库中。

与Javascript兼容的格式可以通过以下方式实现:

arrow.utcnow().isoformat().replace("+00:00", "Z")
'2018-11-30T02:46:40.714281Z'

Javascript的日期。Parse将悄悄地从时间戳中删除微秒。

下面的javascript和python脚本给出相同的输出。我觉得这就是你想要的。

JavaScript

new Date().toISOString()

Python

from datetime import datetime

datetime.utcnow().isoformat()[:-3]+'Z'

它们给出的输出是格式化为ISO字符串的UTC (zulu)时间,其中有一个3毫秒的有效数字,并附加一个Z。

2019-01-19T23:20:25.459Z

选择:isoformat ()

Python的datetime不支持军事时区后缀,比如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)本质上与d.s isoformat(sep=' ')相同

参见:Datetime, Python标准库

选项: strftime()

或者你可以使用strftime来达到同样的效果:

In [4]: d.strftime('%Y-%m-%dT%H:%M:%SZ')
Out[4]: '2014-12-10T12:00:00Z'

注意:此选项仅在您知道指定的日期为UTC时有效。

看到:datetime.strftime ()


附加:人可读时区

更进一步,你可能对显示人类可读的时区信息感兴趣,带strftime %Z时区标志的pytz:

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'

在Python >= 3.2中,你可以简单地使用:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2019-03-14T07:55:36.979511+00:00'

只使用标准库,不假设时区已经是UTC,并返回问题中要求的确切格式:

dt.astimezone(timezone.utc).replace(tzinfo=None).isoformat(timespec='milliseconds') + 'Z'

不过,这确实需要Python 3.6或更高版本。