为什么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

当前回答

通过结合以上所有答案,我得到了以下函数:

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)

其他回答

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

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

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

下面的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

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将悄悄地从时间戳中删除微秒。

简短的回答

datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")

长回答

不包含“Z”的原因是datetime.now()甚至datetime.utcnow()返回的是没有时区信息的datetimes,也就是说没有相关时区信息的datetimes。为了获得一个时区感知的datetime,你需要将一个timezone作为参数传递给datetime.now。例如:

from datetime import datetime, timezone

datetime.utcnow()
#> datetime.datetime(2020, 9, 3, 20, 58, 49, 22253)
# This is timezone naive

datetime.now(timezone.utc)
#> datetime.datetime(2020, 9, 3, 20, 58, 49, 22253, tzinfo=datetime.timezone.utc)
# This is timezone aware

一旦你有了一个时区感知的时间戳,isoformat就会包含一个时区标识。因此,您可以通过以下方式获得ISO 8601时间戳:

datetime.now(timezone.utc).isoformat()
#> '2020-09-03T20:53:07.337670+00:00'

“+00:00”是UTC的有效ISO 8601时区名称。如果你想用“Z”而不是“+00:00”,你必须自己做替换:

datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
#> '2020-09-03T20:53:07.337670Z'

我用钟摆:

import pendulum


d = pendulum.now("UTC").to_iso8601_string()
print(d)

>>> 2019-10-30T00:11:21.818265Z