从sqlite3提取数据时定义时间的问题

时间:2018-10-23 10:36:43

标签: sqlite time charts

我无法正确设置从数据库中提取数据的问题。

我需要提取最后10分钟的数据,并将其放入图表中。我对此有2个问题,我似乎无法获得能够工作以获取特定时间段(最后10分钟)的参数,但我确实设法仅获得了最后600个条目。

可行,但是我的图表X轴是错误的方法,在我将其从数据库中拉出之后,我似乎找不到找到反转表中数据的方法。 (最新的读数向左移动,然后随着您在图表上向右移动而变老)

我目前正在使用的代码是这样(是的,很丑陋,是从各处借来的),但是我希望您可以过去,因为这是我第一次编码这样的代码。

#!/usr/bin/env python

import sqlite3
import sys
import cgi
import cgitb
import time

global variables
speriod=(15)-1 
dbname='/var/www/sensors.db'

def printHTTPheader():
    print "Content-type: text/html\n\n"

def printHTMLHead(title, table):
    print "<head>"
    print "    <title>"
    print title
    print "    </title>"

    print_graph_script(table)

    print "</head>"

#current_time=time.time()

def get_data(interval):

conn=sqlite3.connect(dbname)
curs=conn.cursor()

if interval == None:
    curs.execute("SELECT * FROM readings")
else:
#         curs.execute("SELECT * FROM readings")
    curs.execute("SELECT * FROM readings ORDER BY timestamp DESC LIMIT "+str(600))
#        curs.execute("SELECT * FROM readings WHERE time>=datetime('now','%s minutes')" % interval)

rows=curs.fetchall()

conn.close()

return rows

def create_table(rows):
chart_table=""

for row in rows[:-4]:
    rowstr="['{0}', {1}],\n".format(str(row[2]),str(row[5]))
    chart_table+=rowstr

row=rows[-1]
rowstr="['{0}', {1}]\n".format(str(row[2]),str(row[5]))
chart_table+=rowstr

return chart_table

def print_graph_script(table):

chart_code="""
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['windspeed', 'temperature'],
%s
    ]);
    var options = {
      title: 'windspeed'
    };
    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
</script>"""

print chart_code % (table)

def show_graph():
print "<h2>Windspeed Chart</h2>"
print '<div id="chart_div" style="width: 900px; height: 500px;"></div>'

def show_stats(option):

conn=sqlite3.connect(dbname)
curs=conn.cursor()

if option is None:
    option = str(24)

curs.execute("SELECT timestamp,max(windspeed) FROM readings WHERE time>date('now','-%s hour') AND time<=date('now')" % option)
#    curs.execute("SELECT timestamp,max(windspeed) FROM readings WHERE timestamp>datetime('2013-09-19 21:30:02','-%s hour') AND timestamp<=datetime('2013-09-19 21:31:02')" % option)
rowmax=curs.fetchone()
rowstrmax="{0}&nbsp&nbsp&nbsp{1}C".format(str(rowmax[0]),str(rowmax[1]))

curs.execute("SELECT timestamp,min(windspeed) FROM readings WHERE timestamp>time('time','-%s hour') AND timestamp<=time('current_time')" % option)
#    curs.execute("SELECT timestamp,min(temp) FROM temps WHERE timestamp>datetime('2013-09-19 21:30:02','-%s hour') AND timestamp<=datetime('2013-09-19 21:31:02')" % option)
rowmin=curs.fetchone()
rowstrmin="{0}&nbsp&nbsp&nbsp{1}C".format(str(rowmin[0]),str(rowmin[1]))

curs.execute("SELECT avg(windspeed) FROM readings WHERE timestamp>time('now','-%s hour') AND timestamp<=time('current_time')" % option)
#    curs.execute("SELECT avg(temp) FROM temps WHERE timestamp>datetime('2013-09-19 21:30:02','-%s hour') AND timestamp<=datetime('2013-09-19 21:31:02')" % option)
rowavg=curs.fetchone()

print "<hr>"

print "<h2>Minumum temperature&nbsp</h2>"
print rowstrmin
print "<h2>Maximum temperature</h2>"
print rowstrmax
print "<h2>Average temperature</h2>"
print "%.3f" % rowavg+ "C"

print "<hr>"

print "<h2>In the last hour:</h2>"
print "<table>"
print "<tr><td><strong>Date/Time</strong></td><td> 
<strong>Temperature</strong></td></tr>"

rows=curs.execute("SELECT * FROM readings WHERE timestamp>datetime('now','-1 hour') AND timestamp<=datetime('now')")
#    rows=curs.execute("SELECT * FROM temps WHERE timestamp>datetime('2013-09-19 21:30:02','-1 hour') AND timestamp<=datetime('2013-09-19 21:31:02')")
for row in rows:
    rowstr="<tr><td>{0}&emsp;&emsp;</td><td>{1}C</td></tr>".format(str(row[0]),str(row[1]))
    print rowstr
print "</table>"

print "<hr>"

conn.close()

def print_time_selector(option):

print """<form action="/cgi-bin/webgui.py" method="POST">
    Show the temperature logs for  
    <select name="timeinterval">"""

if option is not None:

    if option == "6":
        print "<option value=\"6\" selected=\"selected\">the last 6 hours</option>"
    else:
        print "<option value=\"6\">the last 6 hours</option>"

    if option == "12":
        print "<option value=\"12\" selected=\"selected\">the last 12 hours</option>"
    else:
        print "<option value=\"12\">the last 12 hours</option>"

    if option == "24":
        print "<option value=\"24\" selected=\"selected\">the last 24 hours</option>"
    else:
        print "<option value=\"24\">the last 24 hours</option>"

else:
    print """<option value="6">the last 6 hours</option>
        <option value="12">the last 12 hours</option>
        <option value="24" selected="selected">the last 24 hours</option>"""

print """        </select>
    <input type="submit" value="Display">
</form>"""


def validate_input(option_str):
if option_str.isalnum():
    if int(option_str) > 0 and int(option_str) <= 24:
        return option_str
    else:
        return None
else: 
    return None

def get_option():
form=cgi.FieldStorage()
if "timeinterval" in form:
    option = form["timeinterval"].value
    return validate_input (option)
else:
    return None

def main():

cgitb.enable()

option=get_option()

if option is None:
    option = str(24)

records=get_data(option)

printHTTPheader()

if len(records) != 0:
    table=create_table(records)
else:
    print "No data found"
    return

print "<html>"
printHTMLHead("Raspberry Pi Wind Logger", table)

print "<body>"
print "<h1>Raspberry Pi Wind Logger</h1>"
    print "<hr>"
    print_time_selector(option)
    show_graph()
    show_stats(option)
    print "</body>"
    print "</html>"

    sys.stdout.flush()

if __name__=="__main__":
    main()

该数据库包含7行(统一时间,日期,时间,风速,方向,温度,校验和),它的数据来自于超声波风传感器,我想在此工作中获得“选项”,就像最大风一样速度或平均风速,但是我认为一旦弄清楚如何真正获得时间排序,这一点就应该变得清楚。

编辑:

这是从数据库中提取的读数

1540300313.94403|23/10/2018|21:11:53|0.1|273|24.1|5E*4B

和用于将数据存储在数据库中的部分代码

 cursor.execute('''insert into readings values (?, ?, ?, ?, ?, ?, ?)''',
 (timestamp, current_date, current_time, windspeed, direction, temperature, checksum));
 dbconnect.commit()

0 个答案:

没有答案