問題出在你的病情(time > datetime.time(17) and time < datetime.time(5))
。 time
不能同時有一個小時> 17和< 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!"
也許類似的crontab /或的TaskScheduler這個?:https://docs.python.org/2/library/sched.html – jmunsch
我計劃使用cron來每小時執行腳本,但我需要能夠解析日誌文件,並且如果時間戳在這兩次之間運行命令 – user3723008
「我打算使用cron ...」注意在這種情況下它將每天運行兩次,一次在5之前,17之後一次。這是你的意圖嗎? – miraculixx