Search code examples
pythondatetimestrptime

python strptime correct format for sub seconds


My datetime data is like this:

2016-03-01 19:25:53.053404

I am trying to use

datetime.strptime(date, "%Y-%m-%d %HH:%MM:%SS")

But I get this error:

ValueError: time data '2016-03-01 19:24:35.165425' does not match format '%Y-%m-%d %HH:%MM:%SS'

How can I fix the format "%Y-%m-%d %HH:%MM:%SS" to match the datetime format that I have?


Solution

  • This is the correct format:

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

    Breakdown:

    • %H: Hour (24-hour clock) as a zero-padded decimal number.
    • %M: Minute as a zero-padded decimal number.
    • %S: Second as a zero-padded decimal number.
    • %f: Microsecond as a decimal number, zero-padded on the left.