sffjunkie / astral

Python calculations for the position of the sun and moon.
Apache License 2.0
236 stars 47 forks source link

Buggy times for northern hemisphere #73

Open AndKe opened 3 years ago

AndKe commented 3 years ago

city = LocationInfo("Tromsø", "Norway", "Europe/Tromsø", 69.65, 18.78)

produces: dawn: 2021-08-29 01:31:26.185793 dusk: 2021-08-29 19:55:29.714044

Real data: https://www.timeanddate.no/astronomi/sol/norge/tromso

yasirroni commented 2 years ago

Can you explain more clearly including the code snippet?

AndKe commented 2 years ago

It was simply about that dawn and dusk times being off with several hours, compared to other sources and experience. If anyone should try to figure it out, this code can be used:

from astral import LocationInfo
from astral.sun import sun
import datetime
import time

def check_date(now):
    city = LocationInfo("Tromsø", "Norway", "Europe/Tromsø", 69.65, 18.78)
    #s = sun(city.observer)  # , date=datetime.date(2021, 2, 18))

    try:
        s = sun(city.observer, date=now)
    except ValueError as ve:
        print (ve)
        if ve == "Sun never reaches 6.0 degrees below the horizon, at this location.":
            print("alwayson")

        if ve == "Sun is always below the horizon on this day, at this location.":
            print("alwaysoff")

    dawn = (s['dawn']) # + datetime.timedelta(hours=0))  # negative hours gives earlier "off"
    dusk = (s['dusk']) # + datetime.timedelta(hours=0))  # positive hours postpone "on"
    dawn = dawn.replace(tzinfo=None)  # remove timezone info
    dusk = dusk.replace(tzinfo=None)

    print(time.strftime('%H:%M:%S'), ', light schedule updated')
    print('dawn: ', dawn)
    print('dusk: ', dusk)
    print('now: ', now)

    if dawn < now:
        print("it is past dawn time")
    if dusk < now:
        print("it is past dusk time")

# for testing

#check_date(datetime.datetime.now())
check_date(datetime.datetime(2021, 8, 29, 23, 59, 59, 342380))