Python strptime wrong format with 12 hour hour

Currently my string format datetime.strptime(date_as_string, '%d/%m/%y %I:%M %p')

this unfortunately does not work with an input such as 1/12/07 00:07 AM

How can I get strptime to re-read this format?

EDIT:

ValueError: time data '1/12/07 00:07 AM' does not match the format '% d /% m /% y% I:% M% p'

+3
source share
2 answers

'00 'is not a valid 12-hour hour, but if your input date string is inconsistently formatted, you can leave with something like this:

>>> from datetime import datetime as dt
>>> date_as_string = '1/12/07 00:07 AM'
>>> format_12 = '%d/%m/%y %I:%M %p'
>>> format_24 = '%d/%m/%y %H:%M %p'
>>> date_string, time_string = date_as_string.split(' ', 1)
>>> try:
...     dt.strptime(date_string + ' ' + time_string, format_12)
... except ValueError:
...     dt.strptime(date_string + ' ' + time_string, format_24)
... 
datetime.datetime(2007, 12, 1, 0, 7)
+4
source

'1/12/07 00:07 AM' has the wrong format, as in the 12-hour format, the hour can be in the range 1-12, and not 0.

+1
source

All Articles