我有一个python程序,它接收和处理数据,但有一个字段没有正确转换。一段数据以java.time.FoffsetDateTime.now(ZoneOffset.UTC(的字符串形式出现,我们使用strptime创建日期时间对象。这是简化的代码:
$ python
from datetime import datetime
# source string format: (java.time.OffsetDateTime.now(ZoneOffset.UTC))
date_string = "2021-06-28T19:47:27.510670082Z"
# this works yet is not in the source format
date_string = "2021-06-28T19:47:27.510670"
datetime_object = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f')
print (datetime_object)
导致此错误的
ValueError: unconverted data remains: 082Z
创建日期时间对象的正确格式代码是什么?
只需使用dateutil
。您有ISO 8601格式的时间,并设置了时区
from dateutil import parser
# source string format: (java.time.OffsetDateTime.now(ZoneOffset.UTC))
date_string = "2021-06-28T19:47:27.510670082Z"
datetime_object = parser.parse(date_string)
print(datetime_object) # 2021-06-28 19:47:27.510670+00:00