Using Astral from a known location

I’ve been working out a minor idea involving the control of some household actions based on local time, but relative to sunrise and sunset rather than a naïve time of day. Simon Kennedy’s Astral is a Python module that can compute these times, but its examples focus on retrieval of locations from major cities. Most places aren’t major cities in the module’s list, so I spent a little time to read the source to determine what other entry points were enabled.

It turns out that the Location class is perfect for those times when you can’t associate a site with a major city, but know the latitude and longitude (from GPS or a mapping service, for example). An example usage follows:

#!/usr/bin/python

"""Example of using astral with a location not in the module's
built-in catalog."""

import astral
import datetime

# From A. Mariano, MacOS units(1), 1993.
FT_PER_METRE = 3.2808399

# Construct our location.  Longitude west and latitude south are
# negative.
los_altos = astral.Location(info=("Los Altos", "USA", 37.3681,
                                  -122.0975, "US/Pacific",
                                  157/FT_PER_METRE))

# "civil", which means 6 degrees below the horizon, is the default
# value for computing dawn and dusk.  But this usage shows how to
# set it before calculation.
los_altos.solar_depression = "civil"

tomorrow = datetime.date.today() + datetime.timedelta(1)

result = los_altos.sun(date=tomorrow)

for k in ["dawn", "sunrise", "noon", "sunset", "dusk"]:
    print "%7s %s" % (k, result[k])