gpt4 book ai didi

Python:这个 datetime.strptime 解析有什么问题?

转载 作者:太空狗 更新时间:2023-10-30 02:53:08 25 4
gpt4 key购买 nike

我尝试将字符串解析为 datetime 对象:

from datetime import datetime
last_time = '2018-06-01T19:00:00.000000000Z'
datetime.strptime(last_time, '%Y-%m-%dT%H:%M:%S.%fZ')

不幸的是,这失败了:

ValueError: time data '2018-06-04T08:44:10.000000000Z' \
does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

我做错了什么?

这描述了解析的参数:

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

最佳答案

参数%f需要微秒精度,检查docs :

When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right. %f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).

所以用 Z 添加最后一个零:

from datetime import datetime
last_time = '2018-06-01T19:00:00.000000000Z'
a = datetime.strptime(last_time, '%Y-%m-%dT%H:%M:%S.%f000Z')

或删除最后 4 个值:

from datetime import datetime
last_time = '2018-06-01T19:00:00.000000000Z'
a = datetime.strptime(last_time[:-4], '%Y-%m-%dT%H:%M:%S.%f')
print (a)
2018-06-01 19:00:00

关于Python:这个 datetime.strptime 解析有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50780492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com