• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

转换时区 pandas 数据框

用户头像
it1352
帮助1

问题说明

我有数据:

                             Symbol      bid      ask
Timestamp                                            
2014-01-01 21:55:34.378000  EUR/USD  1.37622  1.37693
2014-01-01 21:55:40.410000  EUR/USD  1.37624  1.37698
2014-01-01 21:55:47.210000  EUR/USD  1.37619  1.37696
2014-01-01 21:55:57.963000  EUR/USD  1.37616  1.37696
2014-01-01 21:56:03.117000  EUR/USD  1.37616  1.37694

时间戳记为格林尼治标准时间.有没有办法将其转换为东部?

The timestamp is of GMT. Is there a way to convert that to Eastern?

请注意,当我这样做:

data.index

我得到输出:

<class 'pandas.tseries.index.DatetimeIndex'>
[2014-01-01 21:55:34.378000, ..., 2014-01-01 21:56:03.117000]
Length: 5, Freq: None, Timezone: None

正确答案

#1

将索引(使用tz_localize)本地化为UTC(以使Timestamps可以识别时区),然后转换为Eastern(使用tz_convert):

Localize the index (using tz_localize) to UTC (to make the Timestamps timezone-aware) and then convert to Eastern (using tz_convert):

import pytz
eastern = pytz.timezone('US/Eastern')
df.index = index.tz_localize(pytz.utc).tz_convert(eastern)

例如:


For example:

import pandas as pd
import pytz

index = pd.date_range('20140101 21:55', freq='15S', periods=5)
df = pd.DataFrame(1, index=index, columns=['X'])
print(df)
#                      X
# 2014-01-01 21:55:00  1
# 2014-01-01 21:55:15  1
# 2014-01-01 21:55:30  1
# 2014-01-01 21:55:45  1
# 2014-01-01 21:56:00  1

# [5 rows x 1 columns]
print(df.index)
# <class 'pandas.tseries.index.DatetimeIndex'>
# [2014-01-01 21:55:00, ..., 2014-01-01 21:56:00]
# Length: 5, Freq: 15S, Timezone: None

eastern = pytz.timezone('US/Eastern')
df.index = index.tz_localize(pytz.utc).tz_convert(eastern)
print(df)
#                            X
# 2014-01-01 16:55:00-05:00  1
# 2014-01-01 16:55:15-05:00  1
# 2014-01-01 16:55:30-05:00  1
# 2014-01-01 16:55:45-05:00  1
# 2014-01-01 16:56:00-05:00  1

# [5 rows x 1 columns]

print(df.index)
# <class 'pandas.tseries.index.DatetimeIndex'>
# [2014-01-01 16:55:00-05:00, ..., 2014-01-01 16:56:00-05:00]
# Length: 5, Freq: 15S, Timezone: US/Eastern

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcgjghb
系列文章
更多 icon
同类精品
更多 icon
继续加载