同一 pandas DatetimeIndex 对象中具有不同时区的时间戳?

Timestamps with different timezones in the same pandas DatetimeIndex object?

是否可以将由单个时区中的时间戳组成的 pd.DatetimeIndex 转换为每个时间戳都有自己的时间戳,在某些情况下是不同的时区?

这是我想要的示例:

类型(df.index)

 pandas.tseries.index.DatetimeIndex

df.index[0]

Timestamp('2015-06-07 23:00:00+0100', tz='Europe/London')

df.index[1]

Timestamp('2015-06-08 00:01:00+0200', tz='Europe/Brussels') 

如果您很高兴它不是 Index,而是普通的 Series,这应该没问题:

pd.Series([pd.Timestamp('2015-06-07 23:00:00+0100', tz='Europe/London'),
           pd.Timestamp('2015-06-08 00:01:00+0200', tz='Europe/Brussels')])

可以 有一个包含 Timestamps 不同时区的索引。但是您必须明确地将其构造为 Index.

In [33]: pd.Index([pd.Timestamp('2015-06-07 23:00:00+0100', tz='Europe/London'),pd.Timestamp('2015-06-08 00:01:00+0200', tz='Europe/Brussels')],dtype='object')
Out[33]: Index([2015-06-07 23:00:00+01:00, 2015-06-08 00:01:00+02:00], dtype='object')

In [34]: list(pd.Index([pd.Timestamp('2015-06-07 23:00:00+0100', tz='Europe/London'),pd.Timestamp('2015-06-08 00:01:00+0200', tz='Europe/Brussels')],dtype='object'))  
Out[34]: 
[Timestamp('2015-06-07 23:00:00+0100', tz='Europe/London'),
 Timestamp('2015-06-08 00:01:00+0200', tz='Europe/Brussels')]

这是一件非常奇怪的事情,而且完全没有效率。您通常希望有一个 单一 时区表示(UTC 或其他)。在 0.17.0 中,您可以有效地表示带有时区的单个列,因此实现我认为您的目标的一种方法是将不同的时区分隔到不同的列中。参见 docs

将具有不同时区的时间戳添加到同一个 DatetimeIndex 会自动生成一个 DatetimeIndex,其中 UTC 作为默认时区。例如:

In [269]  index = pandas.DatetimeIndex([Timestamp('2015-06-07 23:00:00+0100')])

In [270]  index
Out[270]  DatetimeIndex(['2015-06-07 23:00:00+01:00'], dtype='datetime64[ns, pytz.FixedOffset(60)]', freq=None)

In [271]  index2 = DatetimeIndex([Timestamp('2015-06-08 00:01:00+0200')])

In [272]  index2
Out[272]  DatetimeIndex(['2015-06-08 00:01:00+02:00'], dtype='datetime64[ns, pytz.FixedOffset(120)]', freq=None)

In [273]  index.append(index2)  # returns single index containing both data
Out[273]  DatetimeIndex(['2015-06-07 22:00:00+00:00', '2015-06-07 22:01:00+00:00'], dtype='datetime64[ns, UTC]', freq=None)

注意结果如何是一个 UTC DatetimeIndex,并保留了正确的 UTC 时间戳。

同样:

In [279]  pandas.to_datetime([Timestamp('2015-06-07 23:00:00+0100'), Timestamp('2015-06-08 00:01:00+0200')], utc=True)  # utc=True is needed
Out[279]  DatetimeIndex(['2015-06-07 22:00:00+00:00', '2015-06-07 22:01:00+00:00'], dtype='datetime64[ns, UTC]', freq=None)

这不是一件坏事,因为您可以保留正确的时间,同时能够使用 DatetimeIndex 的索引能力(例如按日期范围切片),同时您可以轻松转换任何其他时区的时间戳(除非你真的需要知道每个时间戳的原始时区,否则这不是理想的)。