Python:安排作业在两个预定义时间之间运行

时间:2014-06-09 15:59:42

标签: python

我试图让命令在两个预定义的时间之间执行;

这是我到目前为止所拥有的

##Time
day_of_week = datetime.date.today().weekday() # 0 is Monday, 6 is Sunday
time = datetime.datetime.now().time()

if day_of_week < 5 and (time > datetime.time(17) and time < datetime.time(5)):  
    print "True"

它似乎在1700之后执行就好了,但是一旦时间翻到第二天,过了0000它根本就没有运行。 任何帮助将非常感激。 感谢

2 个答案:

答案 0 :(得分:1)

time > datetime.time(17) and time < datetime.time(5)

如何能超过17且少于5?

也许:

if ((day_of_week < 5 and time > datetime.time(17)) or
    (0 < day_of_the_week < 6 and time < datetime.time(5))):

答案 1 :(得分:0)

问题出在您的情况(time > datetime.time(17) and time < datetime.time(5))time不能有一小时&gt; 17和&lt; 5同时。

通过一步一步思考这个问题可能会有所帮助:

    ##Time
    from datetime import datetime, date, time, timedelta

    # when to run the job
    time_of_day_min = time(17)
    time_of_day_max = time(5)
    weekdays_min = [0,1,2,3,4] # run Mon-Fri after 17.00
    weekdays_max = [1,2,3,4,5] # run Tue-Sat before 05.00

    # current day and time
    day_of_week = date.today().weekday() # 0 is Monday, 6 is Sunday
    now_time = datetime.now()

    # figure out if it runs between 17.00 - 23.59, or 00.00 - 05.00
    run_before_midnight = now_time >= time_of_day_min 
    run_after_midnight = now_time <= time_of_day_max

    # check if conditions are met. Note the *or*
    if (day_of_week in weekdays_min and run_before_midnight) or \
       (day_of_week in weekdays_max and run_after_midnight):
        print "Running!"