Search code examples
pythonpython-3.xdatetimestrptime

strptime convert string time to time


I try to convert a strign time like this 1:34.21 into a time. I use this datetime.strptime('1:34.21', '%-H:%M.%S').time() to do the conversion but I raise this error:

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'

Solution

  • Just change '%-H:%M.%S' to '%H:%M.%S'

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

    output:

    01:34:21