python strptime wrong format with 12-hour hour
Question
My string format currently is datetime.strptime(date_as_string, '%d/%m/%y %I:%M %p')
this unfortunately does not work with input such as 1/12/07 00:07 AM
How I can get strptime to recogize this format ?
EDIT:
ValueError: time data '1/12/07 00:07 AM' does not match format '%d/%m/%y %I:%M %p'
Solution
'00' is not a valid 12-hour hour, but if your input date string is inconsistently formatted you might be able to get away 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)
OTHER TIPS
'1/12/07 00:07 AM'
has incorrect format because in the 12-hour format the hour can be in range 1-12 and not 0.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow