Let's say I'd want to generate a random integer between 0 and 20 every five seconds, but only when the Datetime is after sunrise and before sunset. This is what I got so far:
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
If I start the code before sunrise time this works, it begins generating random integers as soon as sunrise time == datetime. But it doesn't stop when sunset's here. It just continues with the inner while loop I think, and doesn't check for the datetime anymore, because the inner condition is true.
Could you please give me a hint on how to change the loop so that it stops when sunset is here? And, of course continues the next morning on sunrise etc.
Aucun commentaire:
Enregistrer un commentaire