我是编程新手:(。我有一个sqlite数据库。我从同一个数据库中插入数据和查询数据。它有两列,datetime(文本类型)和0或1(整数)。我想使用python提取此数据并在matplotlib中绘制图。
我尝试过,但是日期时间格式及其转换似乎给我带来了麻烦。我不想使用熊猫,但是虽然无法在matplotlib中获得功能。
import numpy as np
import matplotlib.pyplot as plt
import sqlite3
from datetime import datetime,date
#define datetimes
strt_timestamp=1234567878
end_timestamp=1234568980
#create and connect database and tables
conn=sqlite3.connect('table1.db')
cur=conn.cursor()
#cur.execute('CREATE TABLE machine1(dt_tim TEXT,workingcnd INT)')
conn=sqlite3.connect('table1.db')
cur.execute('DELETE FROM machine1')
#code to create table1 database
while strt_timestamp<=(end_timestamp-54):
strt_timestamp+=55
b=datetime.fromtimestamp(strt_timestamp)
a=b.strftime("%m/%d/%Y,%H:%M:%S");
c=strt_timestamp%2
cur.execute('INSERT INTO machine1(dt_tim,workingcnd)VALUES(?,?)',
(a,c));
cur.execute('SELECT dt_tim,workingcnd FROM machine1');
result=cur.fetchall()
print(result)
cur.execute('SELECT dt_tim FROM machine1')
dt_tim=cur.fetchall()
cur.execute('SELECT workingcnd FROM machine1')
cnd=cur.fetchall()
plt.plot_date(x,y)
plt.show()
答案 0 :(得分:1)
似乎有两个问题。首先,cur.execute('SELECT dt_tim FROM machine1')
的结果是一个元组列表。您需要解压缩它才能获得实际值的列表。
其次,您需要将日期字符串转换为datetime
才能使用matplotlib进行绘制。
import matplotlib.pyplot as plt
import sqlite3
from datetime import datetime
#define datetimes
strt_timestamp=1234567878
end_timestamp=1234568980
#create and connect database and tables
conn=sqlite3.connect('table1.db')
cur=conn.cursor()
#cur.execute('CREATE TABLE machine1(dt_tim TEXT,workingcnd INT)')
conn=sqlite3.connect('table1.db')
#cur.execute('DELETE FROM machine1')
#code to create table1 database
while strt_timestamp<=(end_timestamp-54):
strt_timestamp+=55
b=datetime.fromtimestamp(strt_timestamp)
a=b.strftime("%m/%d/%Y,%H:%M:%S");
c=strt_timestamp%2
cur.execute('INSERT INTO machine1(dt_tim,workingcnd)VALUES(?,?)',
(a,c));
cur.execute('SELECT dt_tim FROM machine1')
dt_tim=[datetime.strptime(d, "%m/%d/%Y,%H:%M:%S") for d, in cur.fetchall()]
cur.execute('SELECT workingcnd FROM machine1')
cnd=[int(d) for d, in cur.fetchall()]
conn.close()
print(dt_tim)
print(cnd)
plt.plot(dt_tim,cnd)
plt.show()