any idea how I figure out if it\'s currently night/day or sunrise/dawn based on time and location of the user?
I haven\'t found anything useful that I c
PyEphem can be used to calculate the time to the next sunrise and sunset. Building upon a blog post I found and the documentation of rise-set, your problem can be solved as follows. Lets assume I am your user, and my location is Oldenburg (Oldb), Germany.
import ephem
user = ephem.Observer()
user.lat = '53.143889' # See wikipedia.org/Oldenburg
user.lon = '8.213889' # See wikipedia.org/Oldenburg
user.elevation = 4 # See wikipedia.org/Oldenburg
user.temp = 20 # current air temperature gathered manually
user.pressure = 1019.5 # current air pressure gathered manually
next_sunrise_datetime = user.next_rising(ephem.Sun()).datetime()
next_sunset_datetime = user.next_setting(ephem.Sun()).datetime()
# If it is daytime, we will see a sunset sooner than a sunrise.
it_is_day = next_sunset_datetime < next_sunrise_datetime
print("It's day." if it_is_day else "It's night.")
# If it is nighttime, we will see a sunrise sooner than a sunset.
it_is_night = next_sunrise_datetime < next_sunset_datetime
print("It's night." if it_is_night else "It's day.")
lat
and lon
need to be strings but ephem does not complain if they are floats.This should work with at least Python 2.7 (with pip-2.7 install pyephem
) and Python 3.2 (with pip-3.2 install ephem
).
Make sure to have a network time protocol client running on the system. E.g. on Debian Linux:
$ sudo apt-get install ntp
$ sudo /etc/init.d/ntp start
Make sure to have the correct timezone set on your system. E.g. on Debian Linux:
$ sudo dpkg-reconfigure tzdata