可以使用python&matplotlib中sqlite数据库的数据绘制datetime而不使用pandas吗?

2024-09-30 12:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手:(。我有一个sqlite数据库,我从中插入和查询数据。它有两列,datetime(键入文本)和0或1(整数)。我想用python和matplotlib中的plot graph来获取这些数据

我试过了,但似乎日期时间格式及其转换给我带来了问题。我不想使用pandas,但未能在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()

Tags: fromimportexecutedatetimematplotlibconnectdtplt
1条回答
网友
1楼 · 发布于 2024-09-30 12:23:43

似乎有两个问题。首先,来自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()

相关问题 更多 >

    热门问题