2013-08-30 58 views
0

我從一個SQLite表日期,我需要在matplotlib圖形顯示爲X.Matplotlib - 如何將日期從SQLite轉換爲matplotlib格式?

"125","2013-08-30 13:33:11" 
"120","2013-08-29 13:33:11" 
"112","2013-08-28 13:33:11" 

我需要用這個日期我:

plt.plot(prices, dates) 

我怎麼能轉換這個日期格式在劇情中使用它?

最好的問候,

+1

那麼,你嘗試過什麼? – tacaswell

回答

5

你想要的日期隱蔽到datetime對象。爲此,請使用適合您數據的格式的datetime.strptime方法。例如,您的數據全是表格

'%Y-%m-%d %H:%M:%S' 

對於year-month-day hour:min:sec。因此,嘗試像

import matplotlib.pyplot as plt 
from matplotlib.dates import datetime as dt 

raw_dates = ["2013-08-30 13:33:11", "2013-08-29 13:33:11", "2013-08-28 13:33:11"] 
x = [dt.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in raw_dates] 
y = [125, 120, 112] 

plt.plot(x, y) 

如果你想調整在x軸上的值(我想他們會顯示爲小時),可以設置DateFormatter。

import matplotlib.pyplot as plt 
from matplotlib.dates import datetime as dt 
from matplotlib.dates import DateFormatter 

formatter = DateFormatter('%m-%d') 

f = plt.figure() 
ax = f.add_subplot(111) 

raw_dates = ["2013-08-30 13:33:11", "2013-08-29 13:33:11", "2013-08-28 13:33:11"] 
x = [dt.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in raw_dates] 
y = [125, 120, 112] 
ax.plot(x, y) 

ax.xaxis.set_major_formatter(formatter) 
plt.show() 

enter image description here

相關問題