从 pandas 时间戳转换时区 [英] Converting timezones from pandas Timestamps

查看:98
本文介绍了从 pandas 时间戳转换时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following in a dataframe:

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

我知道它使用的时区(我认为是GMT),并希望将整个列转换为EST.我怎样才能在 Pandas 中做到这一点?

I know the timezone (I think it is GMT) it uses and would like to convert the entire column to EST. How can I do that in Pandas?

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

For reference, I found these other threads:

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

but they work with datetime timestamps. E.g.:

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

推荐答案

只需使用 tz_convert 方法即可.

Just use tz_convert method.

假设您有一个 Timestamp 对象:

Lets say you have a Timestamp object:

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

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

If you are interested in converting date ranges:

   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_localize:

As stated in another answer, if your data does not have a timezone set, you'll need to tz_localize it:

   data.tz_localize('utc')

这篇关于从 pandas 时间戳转换时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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