python - 从 'yfinance' 下载转换 date 格式

我有一个运行良好的 yfinance 下载,但我希望 Date 列在写入磁盘时采用 YYYY/MM/DD 格式。

Date 列是索引,所以我先删除索引。然后我尝试使用 Pandas' "to_datetime" 和 ".str.replace" 来获取要格式化为 YYYY/MM/DD 的列数据。

这是代码:

import pandas
import yfinance as yf

StartDate_T = '2021-12-20'
EndDate_T = '2022-05-14'

df = yf.download('CSCO', start=StartDate_T, end=EndDate_T, rounding=True)
df.sort_values(by=['Date'], inplace=True, ascending=False)


df.reset_index(inplace=True)  # Make it no longer an Index

df['Date'] = pandas.to_datetime(df['Date'], format="%Y/%m/%d")   # Tried this, but it fails

#df['Date'] = df['Date'].str.replace('-', '/')   # Tried this also - but error re str

file1 = open('test.txt', 'w')
df.to_csv(file1, index=True)
file1.close()

我怎样才能解决这个问题?

回答1

重置索引后更改 date 的格式:

df.reset_index(inplace=True)

df['Date'] = df['Date'].dt.strftime('%Y/%m/%d')

https://stackoverflow.com/questions/52027033/convert-datetime-to-another-format-without-changing-dtype/52027599#52027599 中所述,由于 datetime stores 和 dates 内部的方式,您无法更改格式并保持日期时间格式。所以我会在写入文件(将列更改为字符串格式)之前使用上面的行,然后将其转换回 datetime,以获得 datetime 属性。

df['Date'] = pd.to_datetime(df['Date'])

相似文章

随机推荐

最新文章