将带有微秒的字符串日期时间转换为日期对象

时间:2021-07-18 11:21:50

标签: python-3.x

我有一个来自 json 数据的 datetime 作为 2017-03-28T00:00:00.000Z

我已经试过了

datetime.datetime.strptime(record_date, "%Y-%m-%d%H:%M:%S%f")

但这会导致错误:

*** ValueError: 时间数据 '2017-03-28T00:00:00.000Z' 与格式 '%Y-%m-%d%H:%M:%S%f' 不匹配

我必须将读取日期与用户输入日期作为 2017-03-28 格式进行比较

1 个答案:

答案 0 :(得分:0)

你的时间是isoformat的,你需要使用datetime的fromisoformat将它转换成datetime对象。

[:-1] 是排除 Z 因为日期时间不明白那是什么。 (2017-03-28T00:00:00.000Z 实际上是 RFC 3339)

Z 基本上表示 UTC 时区(+00:00 GMT)

from datetime import datetime
foo = "2017-03-28T00:00:00.000Z"
bar = datetime.fromisoformat(foo[:-1]) 
print(bar)
print(type(bar))

给你结果,但这现在很幼稚(不知道时区)

2017-03-28 00:00:00
<class 'datetime.datetime'>

快速解决时区问题的方法是

bar = datetime.fromisoformat(foo.replace('Z', '+00:00'))
print(bar)
2017-03-28 00:00:00+00:00

#If milliseconds are of concern then just strftime

bar = datetime.fromisoformat(foo.replace('Z', '+00:00')).strftime("%Y-%m-%d %H:%M:%S:%f %Z") 

# the Z displays UTC or equivalent time zone
2017-03-28 00:00:00:000000 UTC

dateutil 模块更擅长处理这个问题,因为它原生支持 RFC 3339。

import dateutil.parser

foo = "2017-03-28T00:00:00.000Z"
bar = dateutil.parser.isoparse(foo)

print(bar)
print(type(bar))

2017-03-28 00:00:00+00:00
<class 'datetime.datetime'>
相关问题