convert 12 hour time to 24 hour time in pandas dataframe
Question:
input
df=pd.DataFrame({
'name':['abc','def','ghi'],
'time':['10:30 PM', '11:30 PM', '01:20 AM']
})
output
name time
0 abc 10:30 PM
1 def 11:30 PM
2 ghi 01:20 AM
I want to like below this which convert 12 hours to 24 hour in time column:
name time
0 abc 22:30
1 def 23:30
2 ghi 01:20
Answers:
use pd.to_datetime
to convert to datetime dtype, and cast to Python time objects via the dt accessor:
df['time'] = pd.to_datetime(df['time']).dt.time
# df['time']
# 0 22:30:00
# 1 23:30:00
# 2 01:20:00
# Name: time, dtype: object
…or add strftime
to get a specific time string format:
df['time'] = pd.to_datetime(df['time']).dt.strftime('%H:%M')
# df['time']
# 0 22:30
# 1 23:30
# 2 01:20
# Name: time, dtype: object
input
df=pd.DataFrame({
'name':['abc','def','ghi'],
'time':['10:30 PM', '11:30 PM', '01:20 AM']
})
output
name time
0 abc 10:30 PM
1 def 11:30 PM
2 ghi 01:20 AM
I want to like below this which convert 12 hours to 24 hour in time column:
name time
0 abc 22:30
1 def 23:30
2 ghi 01:20
use pd.to_datetime
to convert to datetime dtype, and cast to Python time objects via the dt accessor:
df['time'] = pd.to_datetime(df['time']).dt.time
# df['time']
# 0 22:30:00
# 1 23:30:00
# 2 01:20:00
# Name: time, dtype: object
…or add strftime
to get a specific time string format:
df['time'] = pd.to_datetime(df['time']).dt.strftime('%H:%M')
# df['time']
# 0 22:30
# 1 23:30
# 2 01:20
# Name: time, dtype: object