【问题标题】:strptime convert string time to timestrptime 将字符串时间转换为时间
【发布时间】:2021-08-09 18:12:01
【问题描述】:

我尝试将像 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'

【问题讨论】:

    标签: python python-3.x datetime strptime


    【解决方案1】:

    只需将'%-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
    

    【讨论】:

    • 我也试试这个,但有时像问题中的输入格式我有这个错误ValueError: unconverted data remains: 4。例如像2:19.94 这样的时间字符串
    • @th3g3ntl3man 2:19.94 第二次无效。 94 应该是什么?这是第二个吗?还是毫秒?
    猜你喜欢
    • 1970-01-01
    • 2012-02-03
    • 2013-01-25
    • 2021-05-12
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多