gpt4 book ai didi

python - 将 JSON 日期字符串转换为 Python 日期时间

转载 作者:IT老高 更新时间:2023-10-28 12:51:50 26 4
gpt4 key购买 nike

将日期转换为 JSON 时,javascript 会以这种格式保存日期:

2012-05-29T19:30:03.283Z

但是,我不确定如何将其放入 python 日期时间对象中。我试过这些:

# Throws an error because the 'Z' isn't accounted for:
datetime.datetime.strptime(obj[key], '%Y-%m-%dT%H:%M:%S.%f')

# Throws an error because '%Z' doesn't know what to do with the 'Z'
# at the end of the string
datetime.datetime.strptime(obj[key], '%Y-%m-%dT%H:%M:%S.%f%Z')

我相信javascript是把字符串保存为官方ISO格式的,所以看来应该有办法让python的datetime.strptime()读取?

最佳答案

试试下面的格式:

%Y-%m-%dT%H:%M:%S.%fZ

例如:

>>> datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')
datetime.datetime(2012, 5, 29, 19, 30, 3, 283000)

日期中的Z只是表示它应该被解释为UTC时间,所以忽略它不会导致任何信息丢失。您可以在此处找到此信息:http://www.w3.org/TR/NOTE-datetime

关于python - 将 JSON 日期字符串转换为 Python 日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10805589/

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