从'yfinance'下载转换日期格式



我有一个yfinance下载,工作正常,但我希望日期列是在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()

我该如何解决这个问题?

重置索引后更改日期格式:

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

中所述,在不更改dtype的情况下将datetime转换为另一种格式,由于datetime内部存储日期的方式,您无法更改格式并保持datetime格式。因此,我会在写入文件之前使用上面的行(将列更改为字符串格式),然后将其转换回datetime,以具有datetime属性。

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

可以将日期格式传递给to_csv函数:

df.to_csv(file1, date_format='%Y/%m/%d')

最新更新