如何从 yfinance 数据中删除时区?

How to remove the timezone from yfinance data?

我用yfinance包抓取数据。我将它转换成熊猫数据框。 但是,我无法将数据框保存到 excel 文件。

ValueError: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel.

这是数据框的样子。它应该是8列。 Spyder 说它有 7 列。

下面是我的代码:

import yfinance as yf
import pandas as pd

stock = yf.Ticker("BABA")
# get stock info
stock.info

# get historical market data
hist = stock.history(start="2021-03-25",end="2021-05-20",interval="15m")
hist = pd.DataFrame(hist)

# pd.to_datetime(hist['Datetime'])
# hist['Datetime'].dt.tz_localize(None)

hist.to_excel(excel_writer= "D:/data/python projects/stock_BABA2.xlsx")

您可以使用DatetimeIndex.tz_localize()去除DatetimeIndex的时区信息,如下:

hist.index = hist.index.tz_localize(None)

您可以使用 tz_convert() 转换时区,在您的情况下它应该适用于:

hist.index = hist.index.tz_convert(None)