从熊猫时间戳转换时区

Ame*_*ina 11 python timezone pandas

我在数据帧中有以下内容:

> df['timestamps'].loc[0]
Timestamp('2014-09-02 20:24:00')
Run Code Online (Sandbox Code Playgroud)

我知道它使用的时区(我认为它是GMT)并希望将整个列转换为EST.我怎么能在熊猫那里做到这一点?

作为参考,我发现了这些其他线程:

但他们使用datetime时间戳.例如:

> datetime.datetime.fromtimestamp(df['timestamps'].loc[0], tz=None)
returns:

TypeError                                 Traceback (most recent call last)
----> 2 datetime.datetime.fromtimestamp(ts, tz=None)

TypeError: an integer is required (got type Timestamp)
Run Code Online (Sandbox Code Playgroud)

小智 21

只需使用tz_convert方法.

假设您有一个Timestamp对象:

   stamp = Timestamp('1/1/2014 16:20', tz='America/Sao_Paulo')
   new_stamp = stamp.tz_convert('US/Eastern')
Run Code Online (Sandbox Code Playgroud)

如果您有兴趣转换日期范围:

   range = date_range('1/1/2014', '1/1/2015', freq='S', tz='America/Sao_Paulo')
   new_range = range.tz_convert('US/Eastern')
Run Code Online (Sandbox Code Playgroud)

对于大型时间序列:

   import numpy as np
   ts = Series(np.random.randn(len(range)), range)
   new_ts = ts.tz_convert('US/Eastern')
Run Code Online (Sandbox Code Playgroud)

如另一个答案所述,如果您的数据没有设置时区,您需要tz_localize:

   data.tz_localize('utc')
Run Code Online (Sandbox Code Playgroud)

  • 如果我尝试直接使用该列,则相同:`df ['timestamps'].tz_convert('US/Eastern')``TypeError:index不是有效的DatetimeIndex或PeriodIndex` (5认同)
  • 注意:你不能直接在 *column* 上使用 `tz_localize` 或 `tz_convert`,只能在 *index* 上使用 (2认同)

And*_*den 5

datetime 的 fromtimestamp 实际上来自 POSIX 时间戳,即 1970-1-1 GMT 的毫秒

In [11]: datetime.datetime.fromtimestamp?
Type:        builtin_function_or_method
String form: <built-in method fromtimestamp of type object at 0x101d90500>
Docstring:   timestamp[, tz] -> tz's local time from POSIX timestamp.

In [12]: datetime.datetime.fromtimestamp(0)
Out[12]: datetime.datetime(1969, 12, 31, 16, 0)

In [13]: datetime.datetime.fromtimestamp(1)
Out[13]: datetime.datetime(1969, 12, 31, 16, 0, 1)
Run Code Online (Sandbox Code Playgroud)

我认为可能是一个问题,因为我在 PST 时区。

这与 Pandas Timestamp 不同(尽管从 1970-1-1 开始是 ns)。

In [21]: pd.Timestamp(0)
Out[21]: Timestamp('1970-01-01 00:00:00')
Run Code Online (Sandbox Code Playgroud)

要转换 Timestamp/datetime64 列,请使用 tz_convert (如果 tz 天真,即还没有时区,您需要先 tz_localize):

In [31]: pd.Timestamp(0).tz_localize('UTC')
Out[31]: Timestamp('1970-01-01 00:00:00+0000', tz='UTC')

In [32]: t = pd.Timestamp(0).tz_localize('UTC')

In [33]: t.tz_convert('US/Eastern')
Out[33]: Timestamp('1969-12-31 19:00:00-0500', tz='US/Eastern')
Run Code Online (Sandbox Code Playgroud)

请参阅文档时区处理部分