簡體   English   中英

如何在python中將字符串日期(YYYY-MM-DD)從SQL數據庫轉換為matplotlib日期?

[英]How to converting string dates(YYYY-MM-DD) from SQL database to matplotlib dates in python?

我想為溫度和日期數據庫中的數據繪制一個圖表。 數據日期是字符串類型。 我試圖使用date2num()函數將字符串類型轉換為matplot日期。 但是,在繪制圖形時,我觀察到日期以時間形式顯示。 為什么會發生這種情況,我該怎么做才能在X軸上設置格式為(YYYY-MM-DD)的日期?

import MySQLdb
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from dateutil import parser
from matplotlib import style
import datetime
def graph_data():
con =MySQLdb.connect("***.***.*.**","monitor", "password","temp")
cursor=con.cursor()
style.use('fivethirtyeight')
cursor.execute('select tdate,ttime,temperature from temptb')
rows=cursor.fetchall()
timenow=[]
temperature=[]
for eachRow in rows:
    temperature.append(eachRow[2])
    timenow.append(eachRow[0])
#dates=[mdates.date2num(t) for t in timenow]
fig=plt.figure()
ax1=fig.add_subplot(111)
ax1.set_title("Temperature Analysis")
ax1.set_ylabel("Temperature")
ax1.set_xlabel("Time")
#ax1.plot_date(dates, temperature, '-', label="tempurature", color='r')
ax1.plot_date(timenow, temperature, '-', label="tempurature", color='r')
fig.autofmt_xdate(rotation=60)
fig.tight_layout()
ax1.grid(True)
ax1.legend(loc='best', framealpha=0.5)
plt.savefig("figure.png")

graph_data()

從數據庫獲取的數據:2017-12-14 16 2017-12-14 17 2017-12-13 18 2017-12-14 18 2017-12-14 21 2017-12-13 22 2017-12-14 23 2017- 12-13 25 2017-12-14 26

輸出: 溫度圖

編輯1:有在輸出沒有變化,雖然在日期中的ax1.plot_date代替使用timenow(日期,溫度,“ - ”,標記=“tempurature”,顏色=“R”)

您為什么要在datenow中設置date = [mdates.date2num(t)for timenow]?

您有來自數據庫的日期嗎?

我無法完全復制您的代碼; 但是,我假設您數據庫中的數據像這樣返回:2017-12-13、2017-12-14、2017-12-15 在此處輸入圖片說明

如果這些格式正確

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from dateutil import parser
from matplotlib import style
import datetime

timenow=["2017-12-15", "2017-12-14", "2017-12-13"]
temperature=[10,20,30]


fig=plt.figure()
ax1=fig.add_subplot(111)
ax1.set_title("Temperature Analysis")
ax1.set_ylabel("Temperature")
ax1.set_xlabel("Time")
ax1.plot_date(timenow, temperature, '-', label="tempurature", color='r')
fig.autofmt_xdate(rotation=60)
fig.tight_layout()
ax1.grid(True)
ax1.legend(loc='best', framealpha=0.5)
plt.savefig("figure.png")

我只是將ax1.plot_date(dates,temperature,'-',label =“ tempurature”,color ='r')更改為示例中的內容。 我可能理解的問題不對,但是我認為這很簡單。

編輯:嘗試在添加到timenow數組之前添加此內容。

import datetime
t = eachRow[0]


timenow.append(t.strftime('%m/%d/%Y'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM