gpt4 book ai didi

python - 如何将字符串日期(YYYY-MM-DD)从 SQL 数据库转换为 python 中的 matplotlib 日期?

转载 作者:行者123 更新时间:2023-11-30 21:49:36 24 4
gpt4 key购买 nike

我想为数据库中的温度和日期数据绘制图表。数据日期是字符串类型。我尝试使用 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 162017-12-14 172017-12-13 182017-12-14 182017-12-14 212017-12-13 222017-12-14 232017-12-13 252017-12-14 26

输出: tempurature graph

edit 1: There is no change in output though using timenow in the place of date in ax1.plot_date(dates, temperature, '-', label="tempurature", color='r')

最佳答案

你为什么做 dates=[mdates.date2num(t) for t in timenow]?

你的数据库有 tdate 吗?

我无法完全复制您的代码;但是,我假设您的数据库中的数据是这样返回的:2017-12-13, 2017-12-14, 2017-12-15 enter image description here

如果这些格式正确

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'))

关于python - 如何将字符串日期(YYYY-MM-DD)从 SQL 数据库转换为 python 中的 matplotlib 日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47842930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com