我目前在使用 Python 的内置 strptime() 方法将传入的日期时间字符串转换为日期时间对象时遇到问题。这是我目前拥有的:
def fixDateTimeField(datetimeString):
# Convert from 2012-08-07T00:00:00Z to 2012-08-07T00:00:00.000Z
datetime_object = datetime.strptime(datetimeString, "%y-%m-%dT%H:%M:%SZ")
return datetime_object
如评论所述,我正在尝试将字符串“2012-08-07T00:00:00Z”转换为看起来像 2012-08-07T00:00:00.000Z 的日期时间对象,但我在我的控制台显示:"ValueError: time data '2012-08-07T00:00:00Z' does not match format '%y-%m-%dT%H:%M:%SZ'"
。格式对我来说似乎是正确的,但我没有看到问题。
提前致谢!
最佳答案
%y
是两位数的年份。你有一个四位数的年份。
请尝试使用 %Y
。
>>> from datetime import datetime
>>> datetimeString = "2012-08-07T00:00:00Z"
>>> print(datetime.strptime(datetimeString, "%Y-%m-%dT%H:%M:%SZ"))
2012-08-07 00:00:00
关于Python 日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51539728/