convert 12 hour time to 24 hour time in pandas dataframe

ε祈祈猫儿з 提交于 2021-01-29 07:11:30

问题


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

回答1:


use pd.to_datetime to convert to datetime dtype, and cast back to string 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


来源:https://stackoverflow.com/questions/63968442/convert-12-hour-time-to-24-hour-time-in-pandas-dataframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!