【发布时间】:2020-06-24 10:42:01
【问题描述】:
我从数据库中获取了这个日期字符串格式,我需要将其转换为日期时间对象才能进行减法。
'from': '2020-06-24T10:12:00.692+00:00'
我尝试过这种格式,但不起作用。
"%Y-%m-%dT%H:%M:%S.%f%z"
这个字符串在 python 中是否可以转换?
更新: 那是我运行的strptime
datetime_obj1= datetime.strptime(row['from'], "%Y-%m-%dT%H:%M:%S.%f%z")
我得到的错误
ValueError Traceback (most recent call last)
<ipython-input-11-7798f7219c52> in <module>
23 for row in list_of_events:
24 print(row['id'])
---> 25 datetime_obj1= datetime.strptime(row['from'], "%Y-%m-%dT%H:%M:%S%z")
26 print(datetime_obj1)
27 #print(row['from']-row['to'])
/usr/lib/python3.6/_strptime.py in _strptime_datetime(cls, data_string, format)
563 """Return a class cls instance based on the input string and the
564 format string."""
--> 565 tt, fraction = _strptime(data_string, format)
566 tzname, gmtoff = tt[-2:]
567 args = tt[:6] + (fraction,)
/usr/lib/python3.6/_strptime.py in _strptime(data_string, format)
360 if not found:
361 raise ValueError("time data %r does not match format %r" %
--> 362 (data_string, format))
363 if len(data_string) != found.end():
364 raise ValueError("unconverted data remains: %s" %
ValueError: time data '2020-06-24T10:12:00.692+00:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
【问题讨论】:
-
在 Python 3.7+ 上,使用
datetime.fromisoformat('2020-06-24T10:12:00.692+00:00')- 顺便说一下,strptime的格式代码对我来说也很好......
标签: python python-3.x datetime