Close

Tracking Sunset time in Python

A project log for MQTT Porchlight is an Intranet of Thing

Controlling a Wemo light switch with MQTT and Raspberry Pi

Mike SzczysMike Szczys 12/09/2019 at 21:060 Comments

Changing the sundown time with the seasons is a nice feature. It's really easy to do thanks to the Astral library that I learned about in this thread:

https://stackoverflow.com/questions/38986527/sunrise-and-sunset-time-in-python/38986561#38986561

Just give it your location and you can look up the sunrise, sunset for any date. I use this method in a function that updates my scheduled "On" time each day at noon:

def service_sundown(client):
    #Update any schedules with "sundown" in them to match daily changes
    #this should be run every day mid-day
    #print("sundown schedule running")
    sundown_events = [x for x in schedule.jobs if "sundown" in x.tags]
    for event in sundown_events:
        #print(event)
        n = event.next_run
        newsundown = get_sundown(n)
        event.next_run = datetime.datetime(n.year, n.month, n.day, newsundown.hour, newsundown.minute)
        event.at_time = datetime.time(newsundown.hour, newsundown.minute)
        client.publish(topic, payload="Next sundown set for: %s" % event.next_run.strftime("%H:%M"))

Discussions