I have some time input in the format of '10:23:34 PM'
in string and I'd like to convert it to a datetime looking like '22:23:45'
. I'm using
datetime = posts['time'].apply(lambda x: datetime.strptime(x, '%I:%M:%S %p').strftime('%I:%M:%S'))
However, this seems to disregard the AM/PM markers, and all the info comes out as if the time was in the AM, ergo for the '10:23:34 PM'
input I get '10:23:34'
as output, but it should be '22:23:45'
. How can I fix this?
Giving a 2025 update on this question.
You need to pass the format string into pd.to_datetime
, otherwise it pulls in dateutil and slowly parses each element individually (which may not be consistent). %p
handles the AM/PM in the string.
pd.to_datetime(df['time'], format='%I:%M:%S %p')
To extract a clean time value you can then extract the .dt.time
from it.