将datetime.timedelta与datetime.now进行比较

时间:2017-03-20 18:59:09

标签: python datetime raspberry-pi delta

我需要从sql db中设置的时间停止脚本。我的想法是使用If else。

你可以看到我在python中并不是很好但继续前进: - )

我正在使用的脚本下面。

我无法弄清楚如何将timedelta与日期时间进行比较

    #!/usr/bin/python

import MySQLdb as mdb
import sys
import wiringpi as wiringpi
import os
import settings
from time import sleep
from time import time
from datetime import datetime, date, time 

if len(sys.argv) != 2:
        print "Usage: ./thermostat.py <scheduleid>"
        sys.exit()
scheduleid = sys.argv[1]

# Enable GPIO
os.environ['WIRINGPI_GPIOMEM'] = '1'
wiringpi.wiringPiSetupGpio()

# open a database connection
con = mdb.connect(host=settings.SQLSERVER,user=settings.SQLUSER,passwd=settings.SQLPASS,db=settings.SQLDB);

# prepare a cursor object using cursor() method
cursor_actual = con.cursor ()
cursor_target = con.cursor ()
cursor_stats = con.cursor ()
cursor_endtime = con.cursor ()

# execute the SQL query using execute() method.
cursor_actual.execute ("SELECT temperature FROM temperature WHERE timestamp = (SELECT MAX(timestamp) FROM temperature)")
cursor_target.execute (("SELECT targettemp FROM rules WHERE id = %s"),(scheduleid))
cursor_endtime.execute ("SELECT timeend FROM schedules WHERE id = '4'")


# fetch all of the rows from the query
actual = cursor_actual.fetchall()
target = cursor_target.fetchall()
endtime = cursor_endtime.fetchall()

# print the rows
for row in actual:
 actual = row[0]

for row in target:
 target = row[0]

#delta now time
utcnow = datetime.utcnow()
midnight_utc = datetime.combine(utcnow.date(), time(0))
delta = utcnow - midnight_utc

# Switching ON and OFF the boiler
if actual < target and endtime < delta.total_seconds():
    cursor_stats.execute("INSERT INTO stats(timestamp,currenttemp,targettemp,state) VALUES (CURRENT_TIMESTAMP,%s,%s,'ON')",(actual,target))
    print "The temperature is {} and the target temperature is {} so the heating is turned ON".format(actual,target)
    print endtime
    print delta.total_seconds()
    exec settings.on

else:
    cursor_stats.execute("INSERT INTO stats(timestamp,currenttemp,targettemp,state) VALUES (CURRENT_TIMESTAMP,%s,%s,'OFF')",(actual,target))
    print "The temperature is {} and the target temperature is {} so the heating is turned OFF".format(actual,target)
    print endtime
    print delta.total_seconds()
    exec settings.off

# close mysql cleanly
con.commit()
cursor_actual.close ()
cursor_target.close ()
con.close ()

# Exit the script
sys.exit()

脚本的结果如下

pi@Relay-Boiler:~/scripts $ ./3.py 1
The temperature is 21.05 and the target temperature is 40.0 so the heating is turned OFF
((datetime.timedelta(0, 68400),),)
77363.030178

谢谢

0 个答案:

没有答案