Python 从时间戳转换时区

Python 从时间戳转换时区,python,pandas,timezone,Python,Pandas,Timezone,我在数据帧中有以下内容: > df['timestamps'].loc[0] Timestamp('2014-09-02 20:24:00') 我知道它使用的时区(我想它是GMT),并希望将整个列转换为EST。我怎样才能在熊猫身上做到这一点 作为参考,我发现了以下其他线程: 但是它们使用的是datetime时间戳。例如: > datetime.datetime.fromtimestamp(df['timestamps'].loc[0], tz=None) returns:

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

> df['timestamps'].loc[0]
Timestamp('2014-09-02 20:24:00')
我知道它使用的时区(我想它是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)

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)
要转换Timestamp/datetime64列,请使用tz_convert(如果tz是幼稚的,即还没有时区,则需要先进行tz_本地化):


请参阅。

仅使用
tz\u convert
方法

假设您有一个Timestamp对象:

   stamp = Timestamp('1/1/2014 16:20', tz='America/Sao_Paulo')
   new_stamp = stamp.tz_convert('US/Eastern')
如果您对转换日期范围感兴趣:

   range = date_range('1/1/2014', '1/1/2015', freq='S', tz='America/Sao_Paulo')
   new_range = range.tz_convert('US/Eastern')
对于大型时间序列:

   import numpy as np
   ts = Series(np.random.randn(len(range)), range)
   new_ts = ts.tz_convert('US/Eastern')
如另一个答案所述,如果您的数据没有设置时区,您需要
tz_本地化
it:

   data.tz_localize('utc')

谢谢,但当我尝试时:
df['timestamps'][0]。tz_convert('US/Eastern')
我得到:
异常:无法转换tz naive时间戳,如果我尝试直接使用列,请使用tz_localize或localize
相同:
df['timestamps'].tz_convert('US/Eastern'))
类型错误:索引不是有效的DatetimeIndex或PeriodIndex
@user815423426您需要首先进行本地化(如我的答案末尾所述),如果您不知道从哪个时区开始,则无法转换为时区。是的。非常感谢@rhloboNote:您不能直接在列上使用
tz\u localize
tz\u convert
,只能在索引上使用
   import numpy as np
   ts = Series(np.random.randn(len(range)), range)
   new_ts = ts.tz_convert('US/Eastern')
   data.tz_localize('utc')