【问题标题】:datetime.strptime() returns a formatting error with %fdatetime.strptime() 返回带有 %f 的格式错误
【发布时间】:2016-08-02 19:33:37
【问题描述】:

我目前正在尝试将秒数转换为分钟和秒表示法。我正在使用 divmod 并尝试将结果转换为日期时间值。我有以下代码:

from datetime import datetime, timedelta
processtime = 69.009
m, s = divmod(processtime, 60)
m= str(m)
m=m[:1]
s= str(s)
s=s[:5]
processstring= m+ ' ' + s
datetimeprocess = datetime.strptime(processstring, "%M %S.f")

但是每次我这样做我都会得到这个错误:

ValueError: time data '1 9.009' does not match format '%M %S.f'

我很确定我已经匹配了格式,但我不知道问题出在哪里。

【问题讨论】:

    标签: python-2.7 datetime strptime


    【解决方案1】:

    您在f 之前缺少%

    datetimeprocess = datetime.strptime(processstring, "%M %S.%f")
    

    测试结果:

    >>> from datetime import datetime, timedelta
    >>> processstring = '1 9.009'
    >>> datetimeprocess = datetime.strptime(processstring, "%M %S.%f")
    >>> print datetimeprocess
    1900-01-01 00:01:09.009000
    >>> 
    

    【讨论】:

    • @Kprakash 不客气。有时我们只需要第二双眼睛:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多