简体   繁体   中英

Converting 12 Hour to 24 Hour time format in Pandas

I have a Time column consisting of data of type 'str' in the following format:

1        5:21:26 PM
2        5:21:58 PM
3        5:22:22 PM
4        5:22:36 PM
5        7:18:16 PM

I'm trying to convert it into a 24 Hour format that'll look like this:

1        17:21:26
2        17:21:58
3        17:22:22
4        17:22:36
5        19:18:16

I followed the solution presented in a similar question here using the code

df['Time'] = pd.to_datetime(df['Time']).strftime('%H:%M:%S')

Which throws up a frustrating error OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 19:30:37

I've also found that no observation exists for 7:30:37 PM or 19:30:37 in my data frame. The above method works well for the rest of the data as opposed to one particular observation.

Are there any ways to override this error or any alternatives to convert the data in the column?

Please Advise.

Use format parameter with %I:%M:%S %p - here %I is for hours in 12H format and %p for match AM or PM :

df['Time'] = pd.to_datetime(df['Time'], format='%I:%M:%S %p').dt.strftime('%H:%M:%S')
print (df)
       Time
1  17:21:26
2  17:21:58
3  17:22:22
4  17:22:36
5  19:18:16

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM