使用 strptime() 问题解析日期时间值

问题描述

我尝试像这样转换数据

'2021-07-06T07:31:02Z'

使用这种方式到datetime

from datetime import datetime
datetime.strptime(created,'%Y-%m-%dT%H:%M:%s.%fZ')

但得到了错误

time data '2021-07-06T07:31:02Z' does not match format '%Y-%m-%dT%H:%M:%s.%fZ'

我做错了什么?

解决方法

您在代码中使用了 %f,但在字符串示例中没有给出分数。 我尝试了以下有效的方法:

datetime.strptime('2021-07-06T07:31:02Z','%Y-%m-%dT%H:%M:%SZ')
Out[14]: datetime.datetime(2021,7,6,31,2)

因此,要么删除 .%f,要么将分数值添加到您的字符串中。

更多信息:

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior