python - 将 timedelta 的时间转换/使用到日期时间

标签 python pandas datetime

我有一个包含两列的数据框: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/

相关文章:

python - 使用行列表,无论我有 1 行还是 N 行

Python:通过读取 stdout 来关闭 for 循环

Python Pandas - 不要按 y 轴值对条形图进行排序

python - Django url 测试用例

python - 输出 Pandas 数据框中所有列的数据

mysql - 如何将此日期/时间值插入到日期时间字段中

python - 如何根据python中已有的变量给变量赋值?

python - 使用西类牙凉菜汤和 Pandas 刮取时产量有限

python - 根据 DateTimeIndex 更新列

php - 使用 mysql NOW() 函数更新数据库中的行在 PHP 查询中不起作用