首页 文章

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

提问于
浏览
2

我有一个包含两列的数据框:1 timedelta'Time'和1 datetime'DateTime' .

我的timedelta列只包含/显示正常的常规时间,它从不超过24小时 . 它并没有被用作'timedetla',只是'时间' . 它只是当pandas从我的数据库中获取数据时的方式 .

我想要一个新列'NewDateTime',其中包含日期时间的日期和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.然后我计划将timedelta添加到日期时间 .

但是当我尝试做的时候:

df['NewDateTime'] = df['DateTime'].dt.replace(hour=0, minute=0, second=0)

我得 AttributeError: 'DatetimeProperties' object has no attribute 'replace'

1 回答

  • 2

    使用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
    

相关问题