首页 > 解决方案 > Python将小时数添加到数据框的日期时间索引

问题描述

我有一个日期时间索引数据框。我想增加几个小时。我的代码:

from datetime import datetime,timedelta
 df.index = 
DatetimeIndex(['2019-10-01 06:58:45', '2019-10-01 06:59:00',
               '2019-10-01 06:59:15', '2019-10-01 06:59:30',
               '2020-07-18 09:16:30', '2020-07-18 09:16:45'],
              dtype='datetime64[ns]', name='',freq=None)
# add two hours to the index datetime
df.index = df.index.time+timedelta(hours=2)

目前的输出:

TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'

标签: pythonpandasdataframedatetime

解决方案


不需要通话时间

df.index = df.index + pd.Timedelta('2 hour')

推荐阅读