Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Change AM/PM format to 24h

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?

like image 819
lte__ Avatar asked Feb 08 '17 16:02

lte__


People also ask

How do you convert AM PM to 24 hours in python?

How do you convert AM PM to 24 hour time in python? datetime. strptime() function to convert the string to a datetime object, and then using the string method strftime() to output the time in 24-hour format.

How do I change time format in pandas?

The date-time default format is “YYYY-MM-DD”. Hence, December 8, 2020, in the date format will be presented as “2020-12-08”. The datetime format can be changed and by changing we mean changing the sequence and style of the format.

How do I change the datetime format of a column in pandas?

Use astype() to Change datetime to String Format You can use this if the date is already in the format you want it in string form. The below example returns the date as a string with format %Y/%m/%d . dtype of column ConvertedDate will be object ( string ).


1 Answers

You want %H not %I:

In [44]:
d='10:23:34 PM'
pd.to_datetime(d).strftime('%H:%M:%S')

Out[44]:
'22:23:34'

%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

like image 183
EdChum Avatar answered Sep 24 '22 15:09

EdChum