Tuesday, September 27, 2011

Python: Computing sunrise sunset times with ephem

It is incredibly easy to find the sunrise and sunset for the city of Manila using Python and ephem libary. Here is for today, September 28, 2011


import ephem

manila = ephem.city("Manila")
sun    = ephem.Sun()
manila.date="2011/09/28"
sunrise= manila.next_rising(sun)
sunset = manila.next_setting(sun)

print ephem.localtime(sunrise)
print ephem.localtime(sunset )

When run within ipython, it results in


In[xxx]: print ephem.localtime(sunrise)
2011-09-29 05:45:16.000003

In [xxx]: print ephem.localtime(sunset )
2011-09-28 17:48:28.000002



Times returned by ephem are always in UTC, a point which puzzled me for more than 30 minutes, wondering what was wrong! We only have to explicitly call the localtime function.

The ephem library knows some cities already. Here is information about Manila:


ephem.Observer date='2011/9/28 00:00:00' epoch='2000/1/1 12:00:00' long=120:58:56.0 lat=14:36:15.0

elevation=7.9248m horizon=0:00:00.0 temp=15.0C pressure=1012.29834492mBar



What if you live in Angeles City, the Philippines? Here is a modified Python code:

import ephem

# manila = ephem.city("Manila")
# Angeles has longitude, latitude of 15°09'N	120°33'E respectively.
mycity= ephem.Observer()
mycity.long= "120:33"
mycity.lat="15:09"

sun    = ephem.Sun()
mycity.date="2011/09/28"
sunrise= mycity.next_rising(sun)
sunset =mycity.next_setting(sun)
print ephem.localtime(sunrise)
print ephem.localtime(sunset )


Here is the output for Angeles City.


In [xxx]: print ephem.localtime(sunrise)
2011-09-29 05:47:04.000003

In [xxx]: print ephem.localtime(sunset )
2011-09-28 17:50:07.000002


We shall put up an ephemeris data page shortly. To view instructions for installation of PyEphem, please visit
http://free-software-explorations.blogspot.com/2010/07/pyephem-ephemeris-computation-library.html



No comments:

Post a Comment