Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 508
rafforaffo Avatar asked Feb 21 '26 17:02

rafforaffo


1 Answers

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)
like image 174
Eugene Soldatov Avatar answered Feb 23 '26 06:02

Eugene Soldatov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!