Search code examples
pythondatetimestrptime

From string to datetime with or without millisecond


I have a list of strings each of them represent a time with or without milliseconds, e.g.

l = ['03:18:45.2345', '03:19:23'] And I want to convert each string into a datetime object. Now I'm running:

>>> 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'

Hence, the question is: How do I iterate the list converting each element in a datetime object?

The first thought is to have a try..except..:

try:
    print datetime.datetime.strptime(item, "%H:%M:%S.%f")
except:
    print datetime.datetime.strptime(item, "%H:%M:%S")

Is there any way to do that without catching the ValueError?


Solution

  • 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)