python-3.x - 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')
解决方案
如果您想使用日期和时间,可以使用 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]
推荐阅读
- mysql - MySQL 服务器:仅将一些数据库移动到另一个位置
- oracle - 与列匹配后需要获取给定字符串中的最大值
- python-2.7 - 使用 Google Cloud Platform 的简单任务队列:Google PubSub 的问题
- ios - 作为 TableView 数据源的 Swift 通用枚举
- javascript - 从 url 中删除特定字符串并重定向
- javascript - Javascript Mobile Swipe 只能使用一次
- oracle - 分区修剪问题
- tfs - TFS 2018 XAML 构建迁移
- php - /tmp 目录未在实时服务器上清理
- android - 单击TextView(设置为可聚焦)后如何在android上隐藏软键盘?