简体   繁体   English

Python TypeError:比较时间需要整数

[英]Python TypeError: an integer is required comparing times

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). 我的目标是创建一个if语句,将现在的时间与时间表(由开始时间和结束时间定义的时间表)进行比较。

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. 否则,我该如何解决错误。

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 . 最后一行会报错:必须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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM