【问题标题】:Start/Stop a loop at a certain datetime在某个日期时间开始/停止循环
【发布时间】:2021-03-21 00:30:12
【问题描述】:

假设我想每五秒生成一个介于 0 和 20 之间的随机整数,但前提是日期时间在日出之后日落之前。 这是我到目前为止得到的:

from suntime import Sun, SunTimeException
import time, datetime
import random

latitude = 51.51
longitude = -0.13
sun = Sun(latitude, longitude)
today_sr = sun.get_sunrise_time() + datetime.timedelta(hours=1)
today_ss = sun.get_sunset_time() + datetime.timedelta(hours=1) + datetime.timedelta(minutes=6)

sunrise = today_sr.strftime('%H:%M')
sunset = today_ss.strftime('%H:%M')

while True:
    t0 = time.time()
    while (time.strftime("%H:%M",time.localtime(t0)) >= sunrise and time.strftime("%H:%M",time.localtime(t0)) <= sunset) == True:    #Solange Tageszeit >= Sonnenaufgangszeit:
        print ("Sunrise -> Starting...")
        while True:
            print (random.randint(0,30))
            time.sleep(5)   #wait 5 seconds..
    else:
        print (time.strftime("%H:%M",time.localtime(t0)))
        print ("Nighttime")
    time.sleep(60)  #check datetime every 60 seconds

如果我在日出时间之前启动代码,它会在日出时间 == 日期时间后立即开始生成随机整数。但它并没有在日落时停止。它只是继续我认为的内部 while 循环,并且不再检查日期时间,因为内部条件为真。

能否请您告诉我如何更改循环以使其在日落时停止?而且,当然会在第二天早上日出时继续。

【问题讨论】:

    标签: python-3.x datetime time while-loop


    【解决方案1】:

    您在日出后继续打印数字的原因是您的第三个 While 循环(第 5 行)永远不会结束。尝试以下修改:

    while True:
        t0 = time.time()
        while (time.strftime("%H:%M",time.localtime(t0)) >= sunrise and time.strftime("%H:%M",time.localtime(t0)) <= sunset) == True:
            print ("Sunrise -> Starting...")
            while time.strftime("%H:%M",time.localtime(t0)) <= sunset:
               print (random.randint(0,30)) 
                time.sleep(5)   #wait 5 seconds..              
        print (time.strftime("%H:%M",time.localtime(t0)))
        print ("Nighttime") 
        time.sleep(60)  #check datetime every 60 seconds
    

    【讨论】:

    • 通过datetime.timedelta 修改了日出进行检查,不幸的是似乎不适用于您的解决方案
    【解决方案2】:

    我想通了!似乎 python 在我将 today_sr.strftime('%H:%M') 存储在 sunrisesunset 中存在问题。此外,无论如何,我的循环太复杂了。它的工作原理是这样的:

    while True:
        t0 = time.time()
        if (time.strftime("%H:%M",time.localtime(t0))) > (today_sr.strftime('%H:%M')) and (time.strftime("%H:%M",time.localtime(t0))) < (today_ss.strftime('%H:%M')):
            print (random.randint(0,20))
        else:
            print ("nighttime...")
        time.sleep(60)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 2016-06-21
      • 2011-09-25
      • 1970-01-01
      相关资源
      最近更新 更多