Python 日期时间对象

标签 python string datetime strptime

我目前在使用 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/

相关文章:

python - 在 Mac 上的 Python 3 中导入 LLDB?

C++、字符串和指针

java - 在字符串的特殊字符前添加 escape "\"

python - 在 Python 中处理日期/时间的最简单方法是什么?

r - 如何在R中的年、月、日和日期之间双向转换?

python - Unix时差显示延迟

python - 如何将数据框变成一系列列表?

python - 使用单选小部件从模型选择字段中删除 "---------"

Python 正则表达式 : (\w+) not picking up up numbers with 2 digits or less

python - 如何使用 Python 将任何字符串转换为有效的自定义模式?