时间数据“2019-06-02T16:19:27.000-04:00”与格式“%Y-%m-%dT%H:%M:%S.%fZ”不匹配

time data '2019-06-02T16:19:27.000-04:00' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

当我这样做时,我遇到了上面的错误:

datetime.strptime(item['dt'], "%Y-%m-%dT%H:%M:%S.%fZ")

即使我尝试:

datetime.strptime(item['dt'], "%Y-%m-%dT%H:%M:%S.%f")

我得到 未转换的数据仍然存在:-04:00 作为我的错误。

我做错了什么?

根据 datetime.strptimeformat codes,您应该使用 %z 来表示 UTC 偏移:

datetime.strptime('2019-06-02T16:19:27.000-04:00', "%Y-%m-%dT%H:%M:%S.%f%z")

这是因为你有 04:00 而不是 0400 作为 utc 偏移...试试这个:

datetime.datetime.strptime('2019-06-02T16:19:27.000-0400', "%Y-%m-%dT%H:%M:%S.%f%z")

输出:

datetime.datetime(2019, 6, 2, 16, 19, 27, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))

%z 期待像 hhmm

这样的东西

https://docs.python.org/3/library/datetime.html - 查看格式代码