在 pandas 的时间戳中添加偏移量 [英] Adding offset to timestamp in pandas

查看:168
本文介绍了在 pandas 的时间戳中添加偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dataframe df and when I run print(df.index), I get:

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对象,以使

I am trying to modify the datetimeindex object, so that the


  1. 该系列中的第一个时间戳从'2011-08-05 00:00:00-04:00'更改为'2011-08-04 20:00:00'

  2. 系列中的第二张邮票将从'2011-08-05 00:00:00-04:00'到'2011-08-04 21:00:00' , 等等。

  1. First timestamp in the series is changed from '2011-08-05 00:00:00-04:00' to '2011-08-04 20:00:00' and
  2. Second stamp in the series would be changed from '2011-08-05 00:00:00-04:00' to '2011-08-04 21:00:00', and so on.

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

I tried pd.to_datetime(df.index, format='%Y-%m-%d %H:%M:%S'), but it returns the same datetimeindex object as above.

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

It is OK with me if the timestamps are converted to string, so I tried:

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

但是没有代码行达到我的最终目标。

But neither lines of code achieves my end goal.

推荐答案

使用 tz_convert 删除时区 s并添加小时 s:

Use tz_convert for remove timezones and add Hours:

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')

这篇关于在 pandas 的时间戳中添加偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆