我有一个包含两列的数据框:1 个时间增量“时间”和 1 个日期时间“日期时间”。
我的 timedelta 列仅包含/显示正常的常规时间,它永远不会超过 24 小时。它不被用作“timedetla”,只是“时间”。 这就是 pandas 从我的数据库中获取数据时的方式。
我想要一个新列“NewDateTime”,其中日期来自 datetime,时间来自 deltatime。
所以我有这个:
Time DateTime
1 09:01:00 2018-01-01 10:10:10
2 21:43:00 2018-01-01 11:11:11
3 03:20:00 2018-01-01 12:12:12
我想要这个:
Time DateTime NewDateTime
1 09:01:00 2018-01-01 10:10:10 2018-01-01 09:01:00
2 21:43:00 2018-01-01 11:11:11 2018-01-01 21:43:00
3 03:20:00 2018-01-01 12:12:12 2018-01-01 03:20:00
起初我尝试将 DateTime 列的小时、分钟和秒设置为 0。 然后我计划将时间增量添加到日期时间。
但是当我尝试这样做时:
df['NewDateTime'] = df['DateTime'].dt.replace(hour=0, minute=0, second=0)
我得到 AttributeError: 'DatetimeProperties' object has no attribute 'replace'
最佳答案
使用Series.dt.floor
对于删除时间:
df['NewDateTime'] = df['DateTime'].dt.floor('D') + pd.to_timedelta(df['Time'])
#if necesary convert times to strings
#df['NewDateTime'] = df['DateTime'].dt.floor('D') + pd.to_timedelta(df['Time'].astype(str))
print (df)
Time DateTime NewDateTime
1 09:01:00 2018-01-01 10:10:10 2018-01-01 09:01:00
2 21:43:00 2018-01-01 11:11:11 2018-01-01 21:43:00
3 03:20:00 2018-01-01 12:12:12 2018-01-01 03:20:00
关于python - 将 timedelta 的时间转换/使用到日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52001323/