【问题标题】:Convert date format from a 'yfinance' download从 \'yfinance\' 下载转换日期格式
【发布时间】:2023-02-03 10:33:02
【问题描述】:

我有一个财经下载工作正常,但我希望在写入磁盘时日期列为 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()

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

【问题讨论】:

    标签: python pandas dataframe yfinance


    【解决方案1】:

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

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

    正如在Convert datetime to another format without changing dtype,由于datetime 在内部存储日期的方式,您不能更改格式并保留日期时间格式。因此,我会在写入文件之前使用上面的行(将列更改为字符串格式),然后将其转换回日期时间,以具有日期时间属性。

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-31
        • 2021-03-24
        • 1970-01-01
        • 2020-11-24
        • 2017-12-23
        相关资源
        最近更新 更多