代码逻辑:
情况1:while true 会不断循环代码,直到 if statement的“当前时间” 等于 end date,则会打印 代码停止的时间。
情况2:第一个if statement的“当前时间”不等于end date 则会 跳去第二个 if statement,并执行既定的时间条件。以此循环,直到当前的时间等于end date
重点:time.sleep(61)秒是为了防止代码在一分钟内反复运行。因此会让代码休息61秒,然后就可以有执行一次代码的效果了
#必须要用这个package,如果使用 import datetime 会出现代Error。
from datetime import datetime
while True:
time_now = time.strftime("%H:%M", time.localtime()) # control the day in hour, such as 9:10
today_date = datetime.today().date()#control the date, such as 2021-8-13
end_date = '2021/08/17'#set the end date
end_date = datetime.strptime(end_date, '%Y/%m/%d')#translate to datetime format
end_date = datetime.date(end_date)# translate to the format that fits with the time_now variable
if today_date < end_date: #try to stop the coding base on the given end date
if time_now == "12:00": #try to run the code in the specific time
call_api()
time.sleep(61) # need to sleep 61 seconds if you want to run the code one time only
elif time_now == "13:00":
call_api()
time.sleep(61) # need to sleep 61 seconds if you want to run the code one time only
elif time_now == "18:00":
call_api()
time.sleep(61) # need to sleep 61 seconds if you want to run the code one time only
elif time_now =="20:00":
call_api()
time.sleep(61) # need to sleep 61 seconds if you want to run the code one time only
elif time_now =="23:59":
call_api()
time.sleep(61) # need to sleep 61 seconds if you want to run the code one time only
else:
# to better understand when the coding stopped, then it needs to show the stop time message
print("The coding is stoped" + " & " + "stop date:%s & stop time:%s" % (today_date,time_now ))
break
1万+

被折叠的 条评论
为什么被折叠?



