从字符串到带或不带毫秒的日期时间

raf*_*ffo 3 python datetime strptime

我有一个字符串列表,每个字符串代表一个带或不带毫秒的时间,例如

l = ['03:18:45.2345', '03:19:23'] 我想将每个字符串转换为日期时间对象。现在我正在运行:

>>> l = ['03:18:45.2345', '03:19:23']
>>> for item in l:
...     print datetime.datetime.strptime(item, "%H:%M:%S.%f")
... 
1900-01-01 03:18:45.234500
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '03:19:23' does not match format '%H:%M:%S.%f'
Run Code Online (Sandbox Code Playgroud)

因此,问题是:如何迭代转换对象中的每个元素的列表datetime

第一个想法是try..except..

try:
    print datetime.datetime.strptime(item, "%H:%M:%S.%f")
except:
    print datetime.datetime.strptime(item, "%H:%M:%S")
Run Code Online (Sandbox Code Playgroud)

有什么办法可以做到这一点而不抓住ValueError

Eug*_*tov 5

l = ['03:18:45.2345', '03:19:23']
for item in l:
    time_format = "%H:%M:%S.%f" if '.' in item else "%H:%M:%S"
    print datetime.datetime.strptime(item, time_format)
Run Code Online (Sandbox Code Playgroud)