如何为pandas datetime添加时区偏移量?

时间:2016-04-15 13:49:18

标签: python datetime pandas

mydata = [{'datetime' : '2015-09-01 00:00:23.205', 'Timezoneoffset': -5},
      {'datetime' : '2015-09-01 00:41:27.659', 'Timezoneoffset': -6},
      {'datetime' : '2015-09-01 00:13:40.897', 'Timezoneoffset': -1},
      {'datetime' : '2015-09-02 00:42:06.007', 'Timezoneoffset': 5}]
t = pd.DataFrame(mydata)
t.datetime = pd.to_datetime(t.datetime,format='%Y-%m-%d %H:%M:%S.%f')

我想创建第三列,如下所示:

2015-08-31 19:00:23.205
2015-08-31 18:41:27.659
2015-08-31 23:13:40.897
2015-09-01 05:42:06.007

任何帮助表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:3)

构造TimedeltaIndex并将其添加到现有的datetime列:

In [241]:
t['datetime_off'] = t['datetime'] + pd.TimedeltaIndex(t['Timezoneoffset'], unit='h')
t

Out[241]:
   Timezoneoffset                datetime            datetime_off
0              -5 2015-09-01 00:00:23.205 2015-08-31 19:00:23.205
1              -6 2015-09-01 00:41:27.659 2015-08-31 18:41:27.659
2              -1 2015-09-01 00:13:40.897 2015-08-31 23:13:40.897
3               5 2015-09-02 00:42:06.007 2015-09-02 05:42:06.007

答案 1 :(得分:1)

您可以将type Timezoneoffset转换为timedelta64[h](小时),然后添加

In [105]: t['datetime'] + t['Timezoneoffset'].astype('timedelta64[h]')
Out[105]:
0   2015-08-31 19:00:23.205
1   2015-08-31 18:41:27.659
2   2015-08-31 23:13:40.897
3   2015-09-02 05:42:06.007
dtype: datetime64[ns]