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.
pip install astralVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to define a location using `LocationInfo`, retrieve an `Observer` object, and then calculate the sun's key events (dawn, sunrise, noon, sunset, dusk) for a specific date.
For Python < 3.9, install `backports.zoneinfo`: `pip install backports.zoneinfo`. Ensure your code handles `zoneinfo` objects instead of `pytz` timezone objects.
Migrate to using `astral.geocoder.lookup(name, database())` to retrieve `LocationInfo` objects, and then access the `observer` attribute to get the `Observer` object.
Always use timezone-aware `datetime` objects. For Python >= 3.9, use `zoneinfo.ZoneInfo('timezone_name')`. For Python < 3.9, ensure `backports.zoneinfo` is installed and use its `ZoneInfo` for timezone localization.When initializing `GoogleGeocoder`, pass your Google Maps API key as the `api_key` parameter: `GoogleGeocoder(api_key='YOUR_API_KEY')`. For simple location lookups without an API key, use the built-in `astral.geocoder.database()` and `lookup()`.
Be aware of this limitation when performing highly precise solar elevation calculations, particularly for observers at very high altitudes. The documentation indicates the difference is usually negligible for most applications.
Adjust the parameters or handle exceptions for locations where the sun does not meet the expected conditions.
Verify the location and date parameters to ensure they are within valid ranges for sun transit calculations.
Install the Astral library using pip: `pip install astral`.
Update the import statement to: `from astral import LocationInfo`.
Ensure that the 'observer' parameter is provided when calling the 'sun' function, e.g., `sun(observer=location.observer, date=datetime.date.today())`.