我有以下日期时间字符串s
:2017-10-18T04:46:53.553472514Z
我这样赞美:
t = datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')
如何修复ValueError:时间数据
'2017-10-18T04:46:53.553472514Z'
与格式'%Y-%m-%dT%H:%M:%SZ'
不匹配
最佳答案
理论上,
t = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%fZ')
将是正确的格式字符串,因为您也可以使用小数秒。但是它们将需要是微秒。您的时间可能是十亿分之一秒,因为
%f
最多只需要6位数字。因此,您需要执行以下操作:
t = datetime.datetime.strptime(s.split(".")[0], '%Y-%m-%dT%H:%M:%S')
t = t + datetime.timedelta(microseconds=int(s.split(".")[1][:-1])/1000)
print (t)
这可以工作,但可以将纳秒转换为微秒。如果这样做不行,则需要执行其他操作。
关于python - 如何解析以`Z`结尾的日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46906432/