我有一个数据框df,运行print(df.index)时,我得到:

DatetimeIndex(['2011-08-05 00:00:00-04:00', '2011-08-05 01:00:00-04:00',
               '2011-08-05 02:00:00-04:00', '2011-08-05 03:00:00-04:00',
               '2011-08-05 04:00:00-04:00', '2011-08-05 05:00:00-04:00',
               '2011-08-05 06:00:00-04:00', '2011-08-05 07:00:00-04:00',
               '2011-08-05 08:00:00-04:00', '2011-08-05 09:00:00-04:00',
               ...
               '2017-07-30 14:00:00-04:00', '2017-07-30 15:00:00-04:00',
               '2017-07-30 16:00:00-04:00', '2017-07-30 17:00:00-04:00',
               '2017-07-30 18:00:00-04:00', '2017-07-30 19:00:00-04:00',
               '2017-07-30 20:00:00-04:00', '2017-07-30 21:00:00-04:00',
               '2017-07-30 22:00:00-04:00', '2017-07-30 23:00:00-04:00'],
              dtype='datetime64[ns, America/New_York]', name=u'Time', length=52488, freq=None)


我正在尝试修改datetimeindex对象,以便


系列中的第一个时间戳从'2011-08-05 00:00:00-04:00'更改为'2011-08-04 20:00:00'
系列中的第二个标记将从'2011-08-05 00:00:00-04:00'更改为'2011-08-04 21:00:00',依此类推。


我尝试了pd.to_datetime(df.index, format='%Y-%m-%d %H:%M:%S'),但是它返回与上述相同的datetimeindex对象。

如果时间戳转换为字符串,可以接受,所以我尝试了:

df.index.strftime('%Y-%m-%d %H:%M:%S')


但是这两行代码都达不到我的最终目标。

最佳答案

使用tz_convert删除timezone并添加Hour

df.index.tz_convert(None) + pd.offsets.Hour(16)


要么:

df.index.tz_convert(None) + pd.Timedelta(16, unit='h')


样品:

idx = ['2011-08-05 00:00:00-04:00', '2011-08-05 01:00:00-04:00',
       '2011-08-05 02:00:00-04:00', '2011-08-05 03:00:00-04:00']
idx = pd.DatetimeIndex(idx).tz_localize('UTC').tz_convert('America/New_York')
print (idx)
DatetimeIndex(['2011-08-05 00:00:00-04:00', '2011-08-05 01:00:00-04:00',
               '2011-08-05 02:00:00-04:00', '2011-08-05 03:00:00-04:00'],
              dtype='datetime64[ns, America/New_York]', freq=None)

idx = idx.tz_convert(None) + pd.offsets.Hour(16)
print (idx)
DatetimeIndex(['2011-08-05 20:00:00', '2011-08-05 21:00:00',
               '2011-08-05 22:00:00', '2011-08-05 23:00:00'],
              dtype='datetime64[ns]', freq='H')

关于python - 在 Pandas 的时间戳中添加偏移量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47620882/

10-12 16:54
查看更多