1

解析时如何让 strptime 有选择地使用小数秒?我正在寻找一种简洁的方法来解析%Y%m%d-%H:%M:%S.%f%Y%m%d-%H:%M:%S.

使用 %f 我收到错误:

ValueError: time data '20130807-13:42:07' does not match format '%Y%m%d-%H:%M:%S.%f'
4

2 回答 2

2
t = t.rsplit('.', 1)[0]
time.strptime('%Y%m%d-%H:%M:%S.%f', t)

或者只是确保添加一个小数:

if not '.' in t:
    t += '.0'
time.strptime('%Y%m%d-%H:%M:%S.%f', t)

这应该这样做。

于 2013-08-13T18:00:35.157 回答
2

尝试这样的事情:

import time

def timeFormatCheck(input):
    try:
        output = time.strptime(input, '%Y%m%d-%H:%M:%S.%f') #or you could even return
    except ValueError:
        output = time.strptime(input,'%Y%m%d-%H:%M:%S') #or you could even return
    return output

或者如果你想要一个布尔值,试试这个:

import time

def isDecimal(input):
    try:
        time.strptime(input, '%Y%m%d-%H:%M:%S.%f')
        return True
    except ValueError:
        return False
于 2013-08-13T18:03:39.233 回答