Calculating dawn and sunset times using PyEphem

dassouki picture dassouki · Apr 14, 2010 · Viewed 13k times · Source

Is it possible to calculate Dawn, Dusk, and sunset times using PyEphem? I've used PyEphem to produce day and night time, but I didn't find anything on sunset/dusk/dawn

Answer

Richard picture Richard · Sep 4, 2013

The following script will calculate sunrise, sunset, and twilight times using PyEphem. The comments should be adequate to explain what each part is doing.

import ephem

#Make an observer
fred      = ephem.Observer()

#PyEphem takes and returns only UTC times. 15:00 is noon in Fredericton
fred.date = "2013-09-04 15:00:00"

#Location of Fredericton, Canada
fred.lon  = str(-66.666667) #Note that lon should be in string format
fred.lat  = str(45.95)      #Note that lat should be in string format

#Elevation of Fredericton, Canada, in metres
fred.elev = 20

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

sunrise=fred.previous_rising(ephem.Sun()) #Sunrise
noon   =fred.next_transit   (ephem.Sun(), start=sunrise) #Solar noon
sunset =fred.next_setting   (ephem.Sun()) #Sunset

#We relocate the horizon to get twilight times
fred.horizon = '-6' #-6=civil twilight, -12=nautical, -18=astronomical
beg_twilight=fred.previous_rising(ephem.Sun(), use_center=True) #Begin civil twilight
end_twilight=fred.next_setting   (ephem.Sun(), use_center=True) #End civil twilight

Relocating the horizon accounts for light refracting around the curvature of the Earth. PyEphem has the capability to calculate this more exactly given a temperature and pressure, but the U.S. Naval Astronomical Almanac prefers to ignore the atmosphere and simply relocate the horizon. I refer to the USNAA here because it's an authoritative source against which these sorts of calculations can be checked. You can also check answers on NOAA's website.

Note that PyEphem takes and returns values in UTC time. This means that you have to convert your local time to UTC and then convert UTC back to local time to find the answers you're probably looking for. On the date I wrote this answer Fredericton, Canada, in the ADT timezone was 3 hours behind UTC.

For kicks, I've also thrown in a calculation of solar noon. Note that this is an additional hour off from what you'd expect - that's a side-effect of our using daylight savings time.

All this returns:

begin civil twilight: 2013/9/4 09:20:46
sunrise:              2013/9/4 09:51:25
noon:                 2013/9/4 16:25:33
sunset:               2013/9/4 22:58:49
end civil twilight:   2013/9/4 23:29:22

Note that we'd have to subtract 3 hours to convert them to the ADT timezone.

This PyEphem documentation page contains much of the above, though I've tried to both clarify points I found confusing and include the important parts of that link here on StackOverflow.