Astral Library
Astral is a Python package for calculating the times of various aspects of the sun and moon, including dawn, sunrise, noon, sunset, dusk, and moon phases. It also provides functions for solar azimuth and elevation. The library includes a self-contained geocoder for looking up location information by name. The current version is 3.2, and it maintains an active release cadence, frequently adding new features and improvements.
Warnings
- breaking In version 3.0, `astral` migrated from `pytz` to Python's built-in `zoneinfo` for timezone handling. This means for Python versions prior to 3.9, you will need to explicitly install `backports.zoneinfo` to ensure timezone functionality works correctly.
- deprecated The direct use of `astral.Astral()` and accessing cities like `a['London']` is part of an older API and may not function as expected or be supported in future versions. The `Astral` class itself was removed in version 3.0.
- gotcha When passing `datetime` objects to functions like `sun()` or `azimuth()`, if the datetime object is 'naive' (i.e., lacks timezone information), `astral` will assume it represents a UTC time. This can lead to incorrect calculations if the user expects local time.
- gotcha The Google Geocoder (`astral.geocoder.GoogleGeocoder`) requires an API key, as mandated by Google. Attempting to use it without providing a valid API key will result in errors.
- gotcha The `astral` package currently does not adjust solar elevation calculations for changes in observer elevation. While the effect is generally very small, users requiring extreme precision for high elevations might find this behavior unexpected.
Install
-
pip install astral
Imports
- LocationInfo
from astral.location import LocationInfo
- Observer
from astral.geocoder import lookup from astral import Observer
- sun
from astral.sun import sun
- moonphase
from astral.moon import moonphase
- Astral
from astral.geocoder import lookup, database city = lookup("London", database())
Quickstart
import datetime
from astral.location import LocationInfo
from astral.sun import sun
# Define a location
l = LocationInfo('London', 'England', 'Europe/London', 51.5, 0.1)
# Get an Observer object from the LocationInfo
observer = l.observer
# Get sun times for today
today = datetime.date.today()
s = sun(observer, date=today)
print(f"Sun Information for {l.name} on {today}:")
print(f" Dawn: {s['dawn']}")
print(f" Sunrise: {s['sunrise']}")
print(f" Noon: {s['noon']}")
print(f" Sunset: {s['sunset']}")
print(f" Dusk: {s['dusk']}")