首页 > 解决方案 > Pandas - 在 python 中将 hh:mm 和 hh:mm:ss 转换为标准 hh:mm:ss

问题描述

我有一个 pandas 列“小时”,它有每小时的时间,但有些列为 (hour:minute)1:00有些列为24:00:00. 我想将它们全部转换为,1:00:00(即小时:分钟:秒)。我尝试转换为to_datetime,但没有运气。谢谢你的帮助。

df['hour'] = pd.to_datetime(df['hour'], format='%H:%M%:%S', errors='ignore')

标签: python-3.xpandas

解决方案


如果您想使用日期和时间,可以使用 strftime() 并转换为 datetime:

df1 = pd.DataFrame({'hour': ['21:51','11:07:20', '08:33:16', '09:01']})
df1['Clean_hour'] = (df1.hour.apply(lambda x: pd.to_datetime(x).strftime('%H:%M:%S'))
                             .apply(lambda x: pd.to_datetime(x)))

print(df1,df1.dtypes)

       hour Clean_hour
0     21:51   21:51:00
1  11:07:20   11:07:20
2  08:33:16   08:33:16
3     09:01   09:01:00

hour                  object
Clean_hour    datetime64[ns]

推荐阅读