pythondatetime-format

python strptime format with optional bits


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


Solution

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