SatAgro / suntime

Simple sunset and sunrise time calculation python library.
GNU Lesser General Public License v3.0
108 stars 38 forks source link

Sunrise after sunset for NZ coordinates #13

Open tomaszstos opened 4 years ago

tomaszstos commented 4 years ago

The following code prints sunrise at 2020-02-17 19:55:00+00:00 and sunset at 2020-02-17 08:40:00+00:00.

sun = Sun(-21.1814185045857, 149.151316322525)
dt = datetime.fromtimestamp(1581932515)
print(sun.get_sunrise_time(dt))
print(sun.get_sunset_time(dt))
dschwen commented 3 years ago

This is true even for north america (US Mountain time).

dschwen commented 3 years ago

Ended up using pyephem instead:

#!/usr/bin/env python3

import ephem
from datetime import datetime, timedelta

# current time in UTC
now = datetime.utcnow()

#Make an observer
coop = ephem.Observer()

#PyEphem takes and returns only UTC times
coop.date = now.strftime("%Y-%m-%d %H:%M")

#Location 
coop.lon  = str(-112)
coop.lat  = str(44)
coop.elev = 1450

#To get U.S. Naval Astronomical Almanac values, use these settings
coop.pressure= 0
coop.horizon = '-0:34'

times = [
    coop.previous_rising(ephem.Sun()),
    coop.next_rising(ephem.Sun()),
    coop.previous_setting(ephem.Sun()),
    coop.next_setting(ephem.Sun())
]

minute = timedelta(minutes=1)
prev_sunrise, next_sunrise, prev_sunset, next_sunset = [(ephem.localtime(time) - now) / minute for time in times]

print("previous sunrise (minutes): ", prev_sunrise)
print("next sunrise (minutes): ", next_sunrise)
print("previous sunset (minutes): ", prev_sunset)
print("next sunset (minutes): ", next_sunset)
Thornye commented 3 years ago

@tomaszstos It's correct, times given in UTC as indicated by +00:00

Jahor commented 3 years ago

It's incorrect, as when translated to local timezone it causes sunrise to be next day: Sunrise

sun.get_sunrise_time() = 2021-05-16 19:12:00+00:00
sun.get_local_sunrise_time() = 2021-05-17 07:12:00+12:00

Sunset

sun.get_sunset_time() = 2021-05-16 05:22:00+00:00
sun.get_local_sunset_time() = 2021-05-16 17:22:00+12:00
yasirroni commented 2 years ago

In UTC, this is the expected behavior I think. But, in local, it should not be like that.

My solution in https://github.com/SatAgro/suntime/pull/19, just add tz as input and done.

Usage:

import datetime
import pytz
from suntime import Sun, SunTimeException

latitude = 7.7956
longitude = 110.3695
tz = pytz.timezone("Asia/Jakarta")

day = datetime.datetime(2022, 4, 24)
print(tz.utcoffset(day))

sun = Sun(latitude, longitude)
try:
    print("")
    print(datetime.datetime.now())
    print()
    print(sun.get_sunrise_time())
    print(sun.get_sunset_time())
    print("")
    print(sun.get_sunrise_time(tz=tz))
    print(sun.get_sunset_time(tz=tz))