首页 > 解决方案 > strptime 将字符串时间转换为时间

问题描述

我尝试将这样的严格时间转换1:34.21为时间。我用它datetime.strptime('1:34.21', '%-H:%M.%S').time()来进行转换,但我提出了这个错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py", line 341, in _strptime
    raise ValueError("'%s' is a bad directive in format '%s'" %
ValueError: '-' is a bad directive in format '%-H:%M.%S'

标签: pythonpython-3.xdatetimestrptime

解决方案


只需更改'%-H:%M.%S''%H:%M.%S'

from datetime import datetime
s = '1:34.21'
print(datetime.strptime(s, '%H:%M.%S').time())

输出:

01:34:21

推荐阅读