Search code examples
pythondatetimetimeraspberry-pi

Sunrise and Sunset time in Python


I'm currently working on a project that notifies the users when certain activities related to light are triggered. I've done the part related to light. Hence, I need to find an effective way to retrieve sunrise and sunset time in python, since the whole script is written in python. I know there are several libraries out there for other languages, I wonder what the most convenient way is to do this in python.

It will seem pretty much like this, I suppose:

if(sunrise<T<sunset) and (light<threshold):
    notifyUser()

I'd appreciate any help here, have a good one.


Solution

  • I have compared few packages (suntime, suntimes, sunriset, astral) and times sunrise and sunset times returned by them. All of them return local time but you can easily get UTC time as well. This is the result:

    from datetime import date, datetime, timezone, timedelta
    import pytz
    import time
    from suntime import Sun, SunTimeException
    from suntimes import SunTimes
    import sunriset
    import astral, astral.sun
    
    latitude = 52.0691667
    longitude = 19.4805556
    altitude = 0
    tz_poland = pytz.timezone('Europe/Warsaw')
    tz_name = 'Europe/Warsaw'
    for_date = date(2021, 4, 6)
    print('====== suntime ======')
    abd = for_date
    sun = Sun(latitude, longitude)
    today_sr = sun.get_sunrise_time()
    today_ss = sun.get_sunset_time()
    print(today_sr.astimezone(tz_poland))
    print(today_ss.astimezone(tz_poland))
    print('====== suntimes ======')
    sun2 = SunTimes(longitude=longitude, latitude=latitude, altitude=altitude)
    day = datetime(for_date.year, for_date.month, for_date.day)
    print(sun2.risewhere(day, tz_name))
    print(sun2.setwhere(day, tz_name))
    print('====== sunriset ======')
    local = datetime.now()
    utc = datetime.utcnow()
    local_tz = float(((local - utc).days * 86400 + round((local - utc).seconds, -1))/3600)
    number_of_years = 1
    start_date = for_date
    df = sunriset.to_pandas(start_date, latitude, longitude, 2, number_of_years)
    for index, row in df.iterrows():
        print(row['Sunrise'])
        print(row['Sunset'])
        break
    print('====== astral ======')
    l = astral.LocationInfo('Custom Name', 'My Region', tz_name, latitude, longitude)
    s = astral.sun.sun(l.observer, date=for_date)
    print(s['sunrise'].astimezone(tz_poland))
    print(s['sunset'].astimezone(tz_poland))
    

    And the return:

    ====== suntime ======
    2021-04-06 06:05:00+02:00
    2021-04-06 19:16:00+02:00
    ====== suntimes ======
    2021-04-06 06:04:34.000553+02:00
    2021-04-06 19:17:16.000613+02:00
    ====== sunriset ======
    0 days 06:02:52.093465
    0 days 19:16:49.892350
    ====== astral ======
    2021-04-06 06:03:39.792229+02:00
    2021-04-06 19:17:01.188463+02:00
    

    Please note only suntimes package support altitude.