python strptime format with optional bits python strptime format with optional bits python python

python strptime format with optional bits


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


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


I'm late to the party but I found if you don't care about the optional bits this will lop off the .%f for you.

datestring.split('.')[0]