为什么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 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
当前回答
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())
其他回答
下面的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 >= 3.2中,你可以简单地使用:
>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2019-03-14T07:55:36.979511+00:00'
我用钟摆:
import pendulum
d = pendulum.now("UTC").to_iso8601_string()
print(d)
>>> 2019-10-30T00:11:21.818265Z
通过结合以上所有答案,我得到了以下函数:
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)
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())