[英]Convert date format from a 'yfinance' download
我有一個運行良好的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
時間在內部存儲日期的方式,您無法更改格式並保留日期時間格式。 因此,我會在寫入文件之前使用上面的行(將列更改為字符串格式),然后將其轉換回日期時間,以具有日期時間屬性。
df['Date'] = pd.to_datetime(df['Date'])
您可以將日期格式傳遞給to_csv
function:
df.to_csv(file1, date_format='%Y/%m/%d')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.