所以我想讀取 csv 并為資料繪制一個圖。我使用 plotly 燭臺輸出股票資料。但是,我在這里遇到的一些問題很奇怪
start=datetime(2017,6,15,10,22)
end=datetime(2021,12,10,19,59)
df=pd.read_csv("test.csv")
df.head()
從excel讀取資料框的輸出是這樣的
Date Name Open High Low Close
0 12/10/2021 19:59 Apple Inc 179.84 179.85 179.81 179.84
1 12/10/2021 19:58 Apple Inc 179.82 179.82 179.80 179.81
2 12/10/2021 19:57 Apple Inc 179.84 179.84 179.82 179.84
3 12/10/2021 19:56 Apple Inc 179.81 179.82 179.78 179.82
4 12/10/2021 19:55 Apple Inc 179.83 179.83 179.80 179.80
這里我使用 strptime() 將資料轉換為日期時間
dates1=df.iloc[:,0].tolist()
for i in range(len(dates1)):
convertdates1.append(datetime.strptime(dates1[i],'%m/%d/%Y %H:%M'))
convertdates1[0]
但是輸出錯誤
datetime.datetime(2020, 11, 12, 0, 0)
可以看到 12/10/2021 19:59 被轉換成 11/12/2020 00:00,為什么呢?我怎樣才能得到正確的結果?我需要在情節燭臺函式上使用它
fig=go.Figure(data=[go.Candlestick(x=convertdates1,open=open,close=close,high=high,low=low)])
fig.show()
如果需要,資料樣本
Date,Name,Open,High,Low,Close
12/10/2021 19:59,Apple Inc,179.84,179.85,179.81,179.84
12/10/2021 19:58,Apple Inc,179.82,179.82,179.80,179.81
12/10/2021 19:57,Apple Inc,179.84,179.84,179.82,179.84
12/10/2021 19:56,Apple Inc,179.81,179.82,179.78,179.82
uj5u.com熱心網友回復:
對我來說,在熊貓替代品中完美地作業to_datetime:
df.iloc[:,0] = pd.to_datetime(df.iloc[:,0], format='%m/%d/%Y %H:%M')
print (df)
Date Name Open High Low Close
0 2021-12-10 19:59:00 Apple Inc 179.84 179.85 179.81 179.84
1 2021-12-10 19:58:00 Apple Inc 179.82 179.82 179.80 179.81
2 2021-12-10 19:57:00 Apple Inc 179.84 179.84 179.82 179.84
3 2021-12-10 19:56:00 Apple Inc 179.81 179.82 179.78 179.82
測驗您的解決方案并且運行良好:
convertdates1 = []
dates1=df.iloc[:,0].tolist()
for i in range(len(dates1)):
convertdates1.append(datetime.strptime(dates1[i],'%m/%d/%Y %H:%M'))
a = convertdates1[0]
print (a)
2021-12-10 19:59:00
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/382312.html
