如何转换 Pandas 系列值的时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14004545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:33:15  来源:igfitidea点击:

How to convert the time zone of the values of a Pandas Series

datetimenumpytimezonepandas

提问by Yariv

I have a pandas Series with values of type datetime64[ns]. The dates are in EST timezone, and I would like to convert them to UTC timezone.

我有一个值为 type 的Pandas系列datetime64[ns]。日期在 EST 时区,我想将它们转换为 UTC 时区。

E.g.,

例如,

 s=pd.Series(pd.date_range('2012-1-1 1:30',periods=3,freq='min'))

How to convert sto UTC?

如何转换s为UTC?

(Note that I don't actually use date_range()so using its tzparameter is not an option.)

(请注意,我实际上并没有使用,date_range()所以使用它的tz参数不是一个选项。)

回答by Andy Hayden

Update: In recent pandas, you can use the dt accessor to broadcast this:

更新:在最近的Pandas中,您可以使用 dt 访问器来广播:

In [11]: s.dt.tz_localize('UTC')
Out[11]:
0   2012-01-01 01:30:00+00:00
1   2012-01-01 01:31:00+00:00
2   2012-01-01 01:32:00+00:00
dtype: datetime64[ns, UTC]


Here's one way (depending if tz is already set it might be a tz_convertrather than tz_localize):

这是一种方法(取决于 tz 是否已经设置,它可能是 atz_convert而不是tz_localize):

In [21]: from pandas.lib import Timestamp

In [22]: s.apply(lambda x: x.tz_localize('UTC')) 
Out[22]: 
0    2012-01-01 06:30:00+00:00
1    2012-01-01 06:31:00+00:00
2    2012-01-01 06:32:00+00:00