Pandas - Change AM/PM format to 24h

2020-03-26 12:13发布


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?


You want %H not %I:

In [44]:
d='10:23:34 PM'


%I returns the 12-hour clock format, you want %H to return the 24-hour format, see the docs

I think you can do this without using apply here:

datetime = pd.to_datetime(posts['time']).dt.strftime('%H:%M:%S')

Note this gives you strings rather than a datetime