5

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?

apadana
  • 13,456
  • 15
  • 82
  • 98
  • Thanks @bmcculley. I think the error python gives is changed since the other question was posted 6 years ago, so I couldn't find the other answer. – apadana Mar 02 '16 at 21:58

3 Answers3

4

You don't need to include two characters for hours, seconds and minutes in your format string; %S is "Second as a zero-padded decimal number", %H is " Hour (24-hour clock) as a zero-padded decimal number.", etc. It's also worth noting that you're completely missing the symbol for microseconds (%f). You should add that if you want your format_string to work.

Here is a link to the strftime() and strptime() behavior documentation

wpercy
  • 9,636
  • 4
  • 33
  • 45
3

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.
pp_
  • 3,435
  • 4
  • 19
  • 27
2

Per the documentation (I recommend bookmarking that link if you're planning to do any significant work with python dates and times), the correct directives for zero-padded hours, minutes, and seconds, are %H, %M, and %S, respectively (no doubled characters)

Further, your input strings include microseconds, so you'll need to either remove those from the inputs or include the %f directive as well.

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

Henry Keiter
  • 16,863
  • 7
  • 51
  • 80