Home > Software design >  Convert a column to a specific time format which contains different types of time formats in python
Convert a column to a specific time format which contains different types of time formats in python

Time:03-16

This is my data frame

df = pd.DataFrame({
'Time': ['10:00PM', '15:45:00', '13:40:00AM','5:00']
})

    Time
0   10:00PM
1   15:45:00
2   13:40:00AM
3   5:00

I need to convert the time format in a specific format which is my expected output, given below.

     Time
0   22:00:00
1   15:45:00
2   01:40:00
3   05:00:00

I tried using split and endswith function of str which is a complicated solution. Is there any better way to achieve this?

Thanks in advance!

CodePudding user response:

here you go. One thing to mention though 13:40:00AM will result in an error since 13 is a) wrong format as AM/PM only go from 1 to 12 and b) PM (which 13 would be) cannot at the same time be AM :)

Cheers

import pandas as pd

df = pd.DataFrame({'Time': ['10:00PM', '15:45:00', '01:40:00AM', '5:00']})
df['Time'] = pd.to_datetime(df['Time'])

print(df['Time'].dt.time)

<<< 22:00:00
<<< 15:45:00
<<< 01:45:00
<<< 05:00:00
  • Related