Question

There are a lot of threads with questions similar to mine, but I can't find the correct answer.

My goal is to create an if statement that compares the time now to a schedule (the schedule defined by a start time and end time).

I have it working if I put specific numbers in for the schedule, but I need to pass variables into my statement seeing that the schedule is not going to be static.

What I have so far:

import time as sleeptime
from datetime import datetime, time
schedule_list = []
def scheduler():
    conn = pymysql.connect(host='myhost', db='test', user='1234', passwd='123456', autocommit = True)
    cur = conn.cursor()
    query = ("SELECT startTimehour, startTimeminute, endTimehour, endTimeminute FROM schedule WHERE hwID = %s")
    print query
    cur.execute(query, (number))
    for row in cur:
        print row
        door_schedule_list.append(row)
    cur.close()
    conn.close()
    if len(door_schedule_list) > 0:
        start_time_hour = door_schedule_list[0][0]
        start_time_minute = door_schedule_list[0][1]
        end_time_hour = door_schedule_list[0][2]
        end_time_minute = door_schedule_list[0][3]
        print start_time_hour
        print start_time_minute
        print end_time_hour
        print end_time_minute
    while True:
        now = datetime.now()
        #print (door_schedule_list)
        #starttime = time(startTimehour, startTimeminute)
        if time("%d","%d") <= now.time() <= time("%d","%d") % (start_time_hour,  start_time_minute, end_time_hour, end_time_minute): 
            print "Schedule active"
            sleeptime.sleep(20)
        else:
            print "Schedule Inactive"
            sleeptime.sleep(20) 

If there is an easier way to accomplish my goal, please let me know. Otherwise how can I fix the error.

Was it helpful?

Solution

When you do:

if time("%d","%d") <= now.time() <= time("%d","%d") % (start_time_hour,  start_time_minute, end_time_hour, end_time_minute)

the % operator its not doing what you think it should do.

Its not the same:

time("%d" % 5, "%d" % 4)

than

time("%d", "%d") % (5, 4)

the last line will complains with the error: an integer is required.

Also you can:

hours = 5
min = 4
time(hours, min)

So you can change the line to:

if time(start_time_hour, start_time_minute) <= now.time() <= time(end_time_hour, end_time_minute)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top