小编典典

Pandas更改外汇DataFrame的时区

python

我们如何在Pandas DataFrame中更改时区?

我编写了一些简单的代码来读取1分钟EURUSD数据(DateTime / Open / High / Low / Close / Vol)。样本数据位于EST时区,我需要将其转换为UTC。

df.tz_convert(pytz.timezone('UTC'))

失败了。有错误

TypeError:无法转换tz天真时间戳,使用tz_localize进行本地化

来自DAT_ASCII_EURUSD_M1_SmallSample.csv文件的样本数据:

20160103 170000; 1.087010; 1.087130; 1.087010; 1.087130; 0 20160103 170100; 1.087120; 1.087120; 1.087120; 1.087120; 0 20160103 170200; 1.087080; 1.087220; 1.087080; 1.087220; 0 20160104 000100; 1.087830; 1.087840; 1.087640; 1.087640; 0 20160104 000200 ; 1.087640; 1.088220; 1.087640; 1.088220; 0 20160104 000300; 1.088220; 1.088220; 1.088040; 1.088050; 0 20160105 000000; 1.082270; 1.082270; 1.082160; 1.082160; 0 20160105 000100; 1.082160; 1.082160; 1.082130; 1.082140; 0 20160105 000200; 1.082150 ; 1.082240; 1.082150; 1.082240; 0

import pandas as pd
import pytz

filename = "DAT_ASCII_EURUSD_M1_SmallSample.csv"

df = pd.read_csv(filename, sep=";", names=['DateTime','Open','High','Low','Close','Vol'],
                 parse_dates = [0], index_col = 'DateTime')

df.tz_localize(pytz.timezone('US/Eastern'))
df.tz_convert(pytz.timezone('UTC'))

print(df)

阅读 190

收藏
2020-12-20

共1个答案

小编典典

您应该使用:

df = df.tz_localize(pytz.timezone('US/Eastern'))
df = df.tz_convert(pytz.timezone('UTC'))

因为tz_localize这不是就地操作,而是返回一个新的DataFrame。

2020-12-20