将列转换为特定时间格式,其中包含 python 中不同类型的时间格式

Convert a column to a specific time format which contains different types of time formats in python

这是我的数据框

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

我需要将时间格式转换为特定格式,这是我预期的输出,如下所示。

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

我尝试使用 str 的 split 和 endswith 函数,这是一个复杂的解决方案。有没有更好的方法来实现这个?

提前致谢!

给你。有一件事要提到,尽管 13:40:00AM 会导致错误,因为 13 是 a) 格式错误,因为 AM/PM 只能从 1 到 12 和 b) PM(13 会是)不能同时是上午 :)

干杯

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