Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: time data does not match format, optional milliseconds [duplicate]

Right now I have:

timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')

This works great unless I'm converting a string that doesn't have the microseconds. How can I specify that the microseconds are optional (and should be considered 0 if they aren't in the string)?

like image 737
Digant C Kasundra Avatar asked Mar 05 '26 04:03

Digant C Kasundra


2 Answers

You could use a try/except block:

try:
    timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
    timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
like image 92
Alexander Avatar answered Mar 07 '26 18:03

Alexander


What about just appending it if it doesn't exist?

if '.' not in date_string:
    date_string = date_string + '.0'

timestamp = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
like image 20
stevieb Avatar answered Mar 07 '26 16:03

stevieb



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!