Astral v2.0¶
Astral is a python package for calculating the times of various aspects of the sun and phases of the moon.
It can calculate the following
- Dawn
- The time in the morning when the sun is a specific number of degrees below the horizon.
- Sunrise
- The time in the morning when the top of the sun breaks the horizon (asuming a location with no obscuring features.)
- Noon
- The time when the sun is at its highest point directly above the observer.
- Midnight
- The time when the sun is at its lowest point.
- Sunset
- The time in the evening when the sun is about to disappear below the horizon (asuming a location with no obscuring features.)
- Dusk
- The time in the evening when the sun is a specific number of degrees below the horizon.
- Daylight
- The time when the sun is up i.e. between sunrise and sunset
- Night
- The time between astronomical dusk of one day and astronomical dawn of the next
- Twilight
- The time between dawn and sunrise or between sunset and dusk
- The Golden Hour
- The time when the sun is between 4 degrees below the horizon and 6 degrees above.
- The Blue Hour
- The time when the sun is between 6 and 4 degrees below the horizon.
- Time At Elevation
- the time when the sun is at a specific elevation for either a rising or a setting sun.
- Solar Azimuth
- The number of degrees clockwise from North at which the sun can be seen
- Solar Zenith
- The angle of the sun down from directly above the observer
- Solar Elevation
- The number of degrees up from the horizon at which the sun can be seen
- Rahukaalam
- “Rahukaalam or the period of Rahu is a certain amount of time every day that is considered inauspicious for any new venture according to Indian Vedic astrology”.
- Moon Phase
- The phase of the moon for a specified date.
Astral also comes with a geocoder containing a local database that allows you to look up information for a small set of locations (new locations can be added).
Note
The Google Geocoder has been removed. Instead you should use the Google Client for Google Maps Services https://github.com/googlemaps/google-maps-services-python
Examples¶
The following examples demonstrates some of the functionality available in the module
Sun¶
Moon¶
The moon phase method returns an number describing the phase, where the value is between 0 and 27.99. The following lists the mapping of various values to the description of the phase of the moon.
0 .. 6.99 | New moon |
7 .. 13.99 | First quarter |
14 .. 20.99 | Full moon |
21 .. 27.99 | Last quarter |
If for example the number returned was 27.99 then the moon would be almost at the New Moon phase, and if it was 24.00 it would be half way between the Last Quarter and a New Moon.
Note
The moon phase does not depend on your location. However what the moon actually looks like to you does depend on your location. If you’re in the southern hemisphere it looks different than if you were in the northern hemisphere.
See http://moongazer.x10.mx/website/astronomy/moon-phases/ for an example.
For an example of using this library to generate moon phases including the names in various languages and the correct Unicode glyphs see the project by PanderMusubi on Github.
Geocoder¶
Note
Location elevations have been removed from the database. These were added due to a misunderstanding of the affect of elevation on the times of the sun. These are not required for the calculations, only the elevation of the observer above/below the location is needed.
See Effect of Elevation below.
Custom Location¶
If you only need a single location that is not in the database then you can
construct a LocationInfo
and fill in the values, either on
initialization
or set the attributes after initialization:
from astral import LocationInfo
l = LocationInfo()
l.name = 'name'
l.region = 'region'
l.timezone = 'US/Central'
l.latitude = 0.1
l.longitude = 1.2
Note
name and region can be anything you like.
Additional Locations¶
You can add to the list of available locations using the
add_locations()
function and passing either a string
with one line per location or by passing a list containing strings, lists or
tuples (lists and tuples are passed directly to the LocationInfo constructor).
Effect of Elevation¶
Times Of The Sun¶
The times of the sun that you experience depend on what obscurs your view of it. It may either be obscured by the horizon or some other geographical feature (e.g. mountains)
If what obscures you at ground level is the horizon and you are at a elevation above ground level then the times of the sun depends on how far further round the earth you can see due to your elevation (the sun rises earlier and sets later).
The extra angle you can see round the earth is determined by calculating the angle α in the image below based on your elevation above ground level, and adding this to the depression angle for the sun calculations.
Warning
This may not be the correct calculation for the angle round the earth. Please raise an issue if you know how it should be calculated.
If your view is obscured by some other geographical feature than the horizon, then the adjustment angle is based on how far you are above or below the feature and your distance to it.
For the first case i.e. obscured by the horizon you need to pass a single float to the Observer as its elevation. For the second case pass a tuple of 2 floats. The first being the vertical distance to the top of the feature and the second the horizontal distance to the feature.
Elevation Of The Sun¶
Even though an observer’s elevation can significantly affect the times of the sun the same is not true for the elevation angle from the observer to the sun.
As an example the diagram below shows the difference in angle between an observer at ground level and one on the ISS orbiting 408 km above the earth.
The largest difference between the two angles is when the angle at ground level is 1 degree. The difference then is approximately 0.15 degrees.
At the summit of mount Everest (8,848 m) the maximum difference is 0.00338821 degrees.
Due to the very small difference the astral package does not currently adjust the solar elevation for changes in observer elevation.
Note on Localized Timezones¶
When creating a datetime object in a specific timezone do not use the
tzinfo parameter to the datetime constructor. Instead use the
localize()
method provided by pytz on the correct pytz
timezone:
>>> dt = datetime.datetime(2015, 1, 1, 9, 0, 0)
>>> pytz.timezone('Europe/London').localize(dt)
datetime.datetime(2015, 1, 1, 9, 0, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)
Dependencies¶
Astral has one required external Python dependency on pytz.
Cities¶
The module includes location and time zone data for the following cities. The list includes all capital cities plus some from the UK. The list also includes the US state capitals and some other US cities.
Aberdeen, Abu Dhabi, Abu Dhabi, Abuja, Accra, Addis Ababa, Adelaide, Al Jubail, Albany, Albuquerque, Algiers, Amman, Amsterdam, Anchorage, Andorra la Vella, Ankara, Annapolis, Antananarivo, Apia, Ashgabat, Asmara, Astana, Asuncion, Athens, Atlanta, Augusta, Austin, Avarua, Baghdad, Baku, Baltimore, Bamako, Bandar Seri Begawan, Bangkok, Bangui, Banjul, Barrow-In-Furness, Basse-Terre, Basseterre, Baton Rouge, Beijing, Beirut, Belfast, Belgrade, Belmopan, Berlin, Bern, Billings, Birmingham, Birmingham, Bishkek, Bismarck, Bissau, Bloemfontein, Bogota, Boise, Bolton, Boston, Bradford, Brasilia, Bratislava, Brazzaville, Bridgeport, Bridgetown, Brisbane, Bristol, Brussels, Bucharest, Bucuresti, Budapest, Buenos Aires, Buffalo, Bujumbura, Burlington, Cairo, Canberra, Cape Town, Caracas, Cardiff, Carson City, Castries, Cayenne, Charleston, Charlotte, Charlotte Amalie, Cheyenne, Chicago, Chisinau, Cleveland, Columbia, Columbus, Conakry, Concord, Copenhagen, Cotonou, Crawley, Dakar, Dallas, Damascus, Dammam, Denver, Des Moines, Detroit, Dhaka, Dili, Djibouti, Dodoma, Doha, Douglas, Dover, Dublin, Dushanbe, Edinburgh, El Aaiun, Fargo, Fort-de-France, Frankfort, Freetown, Funafuti, Gaborone, George Town, Georgetown, Gibraltar, Glasgow, Greenwich, Guatemala, Hanoi, Harare, Harrisburg, Hartford, Havana, Helena, Helsinki, Hobart, Hong Kong, Honiara, Honolulu, Houston, Indianapolis, Islamabad, Jackson, Jacksonville, Jakarta, Jefferson City, Jerusalem, Juba, Jubail, Juneau, Kabul, Kampala, Kansas City, Kathmandu, Khartoum, Kiev, Kigali, Kingston, Kingston, Kingstown, Kinshasa, Koror, Kuala Lumpur, Kuwait, La Paz, Lansing, Las Vegas, Leeds, Leicester, Libreville, Lilongwe, Lima, Lincoln, Lisbon, Little Rock, Liverpool, Ljubljana, Lome, London, Los Angeles, Louisville, Luanda, Lusaka, Luxembourg, Macau, Madinah, Madison, Madrid, Majuro, Makkah, Malabo, Male, Mamoudzou, Managua, Manama, Manchester, Manchester, Manila, Maputo, Maseru, Masqat, Mbabane, Mecca, Medina, Melbourne, Memphis, Mexico, Miami, Milwaukee, Minneapolis, Minsk, Mogadishu, Monaco, Monrovia, Montevideo, Montgomery, Montpelier, Moroni, Moscow, Moskva, Mumbai, Muscat, N’Djamena, Nairobi, Nashville, Nassau, Naypyidaw, New Delhi, New Orleans, New York, Newark, Newcastle, Newcastle Upon Tyne, Ngerulmud, Niamey, Nicosia, Norwich, Nouakchott, Noumea, Nuku’alofa, Nuuk, Oklahoma City, Olympia, Omaha, Oranjestad, Orlando, Oslo, Ottawa, Ouagadougou, Oxford, P’yongyang, Pago Pago, Palikir, Panama, Papeete, Paramaribo, Paris, Perth, Philadelphia, Phnom Penh, Phoenix, Pierre, Plymouth, Podgorica, Port Louis, Port Moresby, Port of Spain, Port-Vila, Port-au-Prince, Portland, Portland, Porto-Novo, Portsmouth, Prague, Praia, Pretoria, Pristina, Providence, Quito, Rabat, Raleigh, Reading, Reykjavik, Richmond, Riga, Riyadh, Road Town, Rome, Roseau, Sacramento, Saint Helier, Saint Paul, Saint Pierre, Saipan, Salem, Salt Lake City, San Diego, San Francisco, San Jose, San Juan, San Marino, San Salvador, Sana, Sana’a, Santa Fe, Santiago, Santo Domingo, Sao Tome, Sarajevo, Seattle, Seoul, Sheffield, Singapore, Sioux Falls, Skopje, Sofia, Southampton, Springfield, Sri Jayawardenapura Kotte, St. George’s, St. John’s, St. Peter Port, Stanley, Stockholm, Sucre, Suva, Swansea, Swindon, Sydney, T’bilisi, Taipei, Tallahassee, Tallinn, Tarawa, Tashkent, Tbilisi, Tegucigalpa, Tehran, Thimphu, Tirana, Tirane, Tokyo, Toledo, Topeka, Torshavn, Trenton, Tripoli, Tunis, Ulaanbaatar, Ulan Bator, Vaduz, Valletta, Vienna, Vientiane, Vilnius, Virginia Beach, W. Indies, Warsaw, Washington DC, Wellington, Wichita, Willemstad, Wilmington, Windhoek, Wolverhampton, Yamoussoukro, Yangon, Yaounde, Yaren, Yerevan, Zagreb
US Cities¶
Albany, Albuquerque, Anchorage, Annapolis, Atlanta, Augusta, Austin, Baltimore, Baton Rouge, Billings, Birmingham, Bismarck, Boise, Boston, Bridgeport, Buffalo, Burlington, Carson City, Charleston, Charlotte, Cheyenne, Chicago, Cleveland, Columbia, Columbus, Concord, Dallas, Denver, Des Moines, Detroit, Dover, Fargo, Frankfort, Harrisburg, Hartford, Helena, Honolulu, Houston, Indianapolis, Jackson, Jacksonville, Jefferson City, Juneau, Kansas City, Lansing, Las Vegas, Lincoln, Little Rock, Los Angeles, Louisville, Madison, Manchester, Memphis, Miami, Milwaukee, Minneapolis, Montgomery, Montpelier, Nashville, New Orleans, New York, Newark, Oklahoma City, Olympia, Omaha, Orlando, Philadelphia, Phoenix, Pierre, Portland, Portland, Providence, Raleigh, Richmond, Sacramento, Saint Paul, Salem, Salt Lake City, San Diego, San Francisco, Santa Fe, Seattle, Sioux Falls, Springfield, Tallahassee, Toledo, Topeka, Trenton, Virginia Beach, Wichita, Wilmington
Thanks¶
The sun calculations in this module were adapted, for Python, from the spreadsheets on the following page.
Refraction calculation is taken from
Sun-Pointing Programs and Their AccuracyJohn C. Zimmerman Of Sandia National Laboratones
Which cites the following as the original source
In Solar Energy Vol 20 No.5-CRobert Walraven Of The University Of California, Davis
The moon phase calculation is based on some javascript code from Sky and Telescope magazine
Moon-phase calculationRoger W. Sinnott, Sky & Telescope, June 16, 2006.
Also to Sphinx for making doc generation an easy thing (not that the writing of the docs is any easier.)
Contact¶
Simon Kennedy <sffjunkie+code@gmail.com>
Version History¶
Version | Description |
---|---|
2.0 | Now only compatible with Python 3.6 and greater due to the use of data classes New New Geocoder functions return a All calculations now automatically adjust for refraction. For elevation you can return the true angle by setting the with_refraction parameter to False. The solar_noon and solar_midnight functions have been renamed to
Rahukaalam can now be calculated for night times. The Google geocoder and Astral classes have been removed |
1.10.1 | Keyword args are now passed to the geocoder class from Astral __init__ in order to allow the Google Maps API key to be passed to the GoogleGeocoder. |
1.10 | Added support to AstralGeocoder to add additional locations to the database. |
1.9.2 | 1.9 broke the sun_utc method. Sun UTC calculation passed incorrect parameter to more specific methods e.g. sunrise, sunset etc. |
1.9.1 | Correct version number in astral.py |
1.9 | Now takes elevation into account. |
1.8 | Location methods now allow the timezone to be None which returns all times as UTC. Added command line interface to return ‘sun’ values |
1.7.1 | Changed GoogleGeocoder test to not use raise…from as this is not valid for Python 2 |
1.7 | Requests is now only needed when using GoogleGeocoder GoogleGeocoder now requires the api_key parameter to be passed to the constructor as Google now require it for their API calls. |
1.6.1 | Updates for Travis CI integration / Github signed release. |
1.6 | Added api_key parameter to the GoogleGeocoder __init__()
method |
1.5 | Added parameter rtype to Added example for calculating the phase of the moon. |
1.4.1 | Using versioneer to manage version numbers |
1.4 | Changed to use calculations from NOAA spreadsheets Changed some exception error messages for when sun does not reach a requested elevation. Added more tests |
1.3.4 | Changes to project configuration files. No user facing changes. |
1.3.3 | Fixed call to twilight_utc as date and direction parameters were reversed. |
1.3.2 | Updated URL to point to gitgub.com Added Apache 2.0 boilerplate to source file |
1.3.1 | Added LICENSE file to sdist |
1.3 | Corrected solar zenith to return the angle from the vertical. Added solar midnight calculation. |
1.2 | Added handling for when unicode literals are used. This may possibly affect your code if you’re using Python 2 (there are tests for this but they may not catch all uses.) (Bug 1588198) Changed timezone for Phoenix, AZ to America/Phoenix (Bug 1561258) |
1.1 | Added methods to calculate Twilight, the Golden Hour and the Blue Hour. |
1.0 | It’s time for a version 1.0 Added examples where the location you want is not in the Astral geocoder. |
0.9 | Added a method to calculate the date and time when the sun is at a specific elevation, for either a rising or a setting sun. Added daylight and night methods to Location and Astral classes. Rahukaalam methods now return a tuple. |
0.8.2 | Fix for moon phase calcualtions which were off by 1. Use pytz.timezone().localize method instead of passing tzinfo parameter to datetime.datetime. See the pytz docs for info |
0.8.1 | Fix for bug 1417641: Added Added tzinfo as an alias for tz |
0.8 | Fix for bug 1407773: Moon phase calculation changed to remove time zone parameter (tz) as it is not required for the calculation. |
0.7.5 | Fix for bug 1402103: Buenos Aires incorrect timezone |
0.7.4 | Added Canadian cities from Yip Shing Ho |
0.7.3 | Fix for bug 1239387 submitted by Torbjörn Lönnemark |
0.7.2 | Minor bug fix in GoogleGeocoder . location name and
region are now stripped of whitespace |
0.7.1 | Bug fix. Missed a vital return statement in the
GoogleGeocoder |
0.7 | Added ability to lookup location information from
Google’s mapping APIs (see Renamed Renamed Added elevations of cities to database and property to
obtain elevation from |
0.6.2 | Added various cities to database as per https://bugs.launchpad.net/astral/+bug/1040936 |
0.6.1 | Docstrings were not updated to match changes to code. Other minor docstring changes made |
0.6 | Fix for bug 884716 submitted by Martin Heemskerk regarding moon phase calculations Fixes for bug report 944754 submitted by Hajo Werder
|
0.5 | Changed Moved city information into a database class Added attribute access to database for timezone groups |
0.4 | Duplicate city names could not be accessed. Sun calculations for some cities failed with times outside valid ranges. Fixes for city data. Added calculation for moon phase. |
0.3 | Changed to Apache V2.0 license. Fix for bug 555508 submitted by me. US state capitals and other cities added. |
0.2 | Fix for bug 554041 submitted by Derek_ / John Dimatos |
0.1 | First release |
The astral
Package¶
Calculations for the position of the sun and moon.
The astral
package provides the means to calculate the following times of the sun
- dawn
- sunrise
- noon
- midnight
- sunset
- dusk
- daylight
- night
- twilight
- blue hour
- golden hour
- rahukaalam
plus solar azimuth and elevation at a specific latitude/longitude. It can also calculate the moon phase for a specific date.
The package also provides a self contained geocoder to turn a small set of
location names into timezone, latitude and longitude. The lookups
can be perfomed using the lookup()
function defined in
astral.geocoder
Note
The Astral and GoogleGeocoder classes from earlier versions have been removed.
-
class
astral.
Depression
¶ The depression angle in degrees for the dawn/dusk calculations
-
class
astral.
SunDirection
¶ Direction of the sun either RISING or SETTING
-
class
astral.
Observer
(latitude: float = 51.4733, longitude: float = -0.0008333, elevation: Union[float, Tuple[float, float]] = 0.0)¶ Defines the location of an observer on Earth.
Latitude and longitude can be set either as a float or as a string. For strings they must be of the form
degrees°minutes’seconds”[N|S|E|W] e.g. 51°31’Nminutes’ & seconds” are optional.
Elevations are either
- A float that is the elevation in metres above a location, if the nearest obscuring feature is the horizon
- or a tuple of the elevation in metres and the distance in metres to the nearest obscuring feature.
Parameters: - latitude – Latitude - Northern latitudes should be positive
- longitude – Longitude - Eastern longitudes should be positive
- elevation – Elevation and/or distance to nearest obscuring feature in metres above/below the location.
-
class
astral.
LocationInfo
(name: str = 'Greenwich', region: str = 'England', timezone: str = 'Europe/London', latitude: float = 51.4733, longitude: float = -0.0008333)¶ Defines a location on Earth.
Latitude and longitude can be set either as a float or as a string. For strings they must be of the form
degrees°minutes’seconds”[N|S|E|W] e.g. 51°31’Nminutes’ & seconds” are optional.
Parameters: - name – Location name (can be any string)
- region – Region location is in (can be any string)
- timezone – The location’s time zone (a list of time zone names can be obtained from pytz.all_timezones)
- latitude – Latitude - Northern latitudes should be positive
- longitude – Longitude - Eastern longitudes should be positive
-
observer
¶ Return an Observer at this location
-
astral.
now
(tzinfo: datetime.tzinfo = <UTC>) → datetime.datetime¶ Returns the current time in the specified time zone
-
astral.
today
(tzinfo: datetime.tzinfo = <UTC>) → datetime.date¶ Returns the current date in the specified time zone
-
astral.
dms_to_float
(dms: Union[str, float, Tuple[float, float]], limit: float = -1) → float¶ Converts as string of the form degrees°minutes’seconds”[N|S|E|W], or a float encoded as a string, to a float
N and E return positive values S and W return negative values
Parameters: - dms – string to convert
- limit – Limit the value between ± limit
Returns: The number of degrees as a float
astral.sun¶
-
astral.sun.
sun
(observer: astral.Observer, date: Optional[datetime.date] = None, dawn_dusk_depression: Union[float, astral.Depression] = <Depression.CIVIL: 6.0>, tzinfo: datetime.tzinfo = <UTC>) → Dict[KT, VT]¶ Calculate all the info for the sun at once.
Parameters: - observer – Observer for which to calculate the times of the sun
- date – Date to calculate for. Default is today’s date in the timezone tzinfo.
- dawn_dusk_depression – Depression to use to calculate dawn and dusk. Default is for Civil dusk i.e. 6.0
- tzinfo – Timezone to return times in. Default is UTC.
Returns: Dictionary with keys
dawn
,sunrise
,noon
,sunset
anddusk
whose values are the results of the corresponding functions.Raises: ValueError
– if passed through from any of the functions
-
astral.sun.
dawn
(observer: astral.Observer, date: Optional[datetime.date] = None, depression: Union[float, astral.Depression] = <Depression.CIVIL: 6.0>, tzinfo: datetime.tzinfo = <UTC>) → datetime.datetime¶ Calculate dawn time.
Parameters: - observer – Observer to calculate dawn for
- date – Date to calculate for. Default is today’s date in the timezone tzinfo.
- depression – Number of degrees below the horizon to use to calculate dawn. Default is for Civil dawn i.e. 6.0
- tzinfo – Timezone to return times in. Default is UTC.
Returns: Date and time at which dawn occurs.
Raises: ValueError
– if dawn does not occur on the specified date
-
astral.sun.
sunrise
(observer: astral.Observer, date: Optional[datetime.date] = None, tzinfo: datetime.tzinfo = <UTC>) → datetime.datetime¶ Calculate sunrise time.
Parameters: - observer – Observer to calculate sunrise for
- date – Date to calculate for. Default is today’s date in the timezone tzinfo.
- tzinfo – Timezone to return times in. Default is UTC.
Returns: Date and time at which sunrise occurs.
Raises: ValueError
– if the sun does not reach the horizon on the specified date
-
astral.sun.
noon
(observer: astral.Observer, date: Optional[datetime.date] = None, tzinfo: datetime.tzinfo = <UTC>) → datetime.datetime¶ Calculate solar noon time when the sun is at its highest point.
Parameters: - observer – An observer viewing the sun at a specific, latitude, longitude and elevation
- date – Date to calculate for. Default is today for the specified tzinfo.
- tzinfo – Timezone to return times in. Default is UTC.
Returns: Date and time at which noon occurs.
-
astral.sun.
midnight
(observer: astral.Observer, date: Optional[datetime.date] = None, tzinfo: datetime.tzinfo = <UTC>) → datetime.datetime¶ Calculate solar midnight time.
Note
This calculates the solar midnight that is closest to 00:00:00 of the specified date i.e. it may return a time that is on the previous day.
Parameters: - observer – An observer viewing the sun at a specific, latitude, longitude and elevation
- date – Date to calculate for. Default is today for the specified tzinfo.
- tzinfo – Timezone to return times in. Default is UTC.
Returns: Date and time at which midnight occurs.
-
astral.sun.
sunset
(observer: astral.Observer, date: Optional[datetime.date] = None, tzinfo: datetime.tzinfo = <UTC>) → datetime.datetime¶ Calculate sunset time.
Parameters: - observer – Observer to calculate sunset for
- date – Date to calculate for. Default is today’s date in the timezone tzinfo.
- tzinfo – Timezone to return times in. Default is UTC.
Returns: Date and time at which sunset occurs.
Raises: ValueError
– if the sun does not reach the horizon
-
astral.sun.
dusk
(observer: astral.Observer, date: Optional[datetime.date] = None, depression: Union[float, astral.Depression] = <Depression.CIVIL: 6.0>, tzinfo: datetime.tzinfo = <UTC>) → datetime.datetime¶ Calculate dusk time.
Parameters: - observer – Observer to calculate dusk for
- date – Date to calculate for. Default is today’s date in the timezone tzinfo.
- depression – Number of degrees below the horizon to use to calculate dusk. Default is for Civil dusk i.e. 6.0
- tzinfo – Timezone to return times in. Default is UTC.
Returns: Date and time at which dusk occurs.
Raises: ValueError
– if dusk does not occur on the specified date
-
astral.sun.
daylight
(observer: astral.Observer, date: Optional[datetime.date] = None, tzinfo: datetime.tzinfo = <UTC>) → Tuple[datetime.datetime, datetime.datetime]¶ Calculate daylight start and end times.
Parameters: - observer – Observer to calculate daylight for
- date – Date to calculate for. Default is today’s date in the timezone tzinfo.
- tzinfo – Timezone to return times in. Default is UTC.
Returns: A tuple of the date and time at which daylight starts and ends.
Raises: ValueError
– if the sun does not rise or does not set
-
astral.sun.
night
(observer: astral.Observer, date: Optional[datetime.date] = None, tzinfo: datetime.tzinfo = <UTC>) → Tuple[datetime.datetime, datetime.datetime]¶ Calculate night start and end times.
Night is calculated to be between astronomical dusk on the date specified and astronomical dawn of the next day.
Parameters: - observer – Observer to calculate night for
- date – Date to calculate for. Default is today’s date for the specified tzinfo.
- tzinfo – Timezone to return times in. Default is UTC.
Returns: A tuple of the date and time at which night starts and ends.
Raises: ValueError
– if dawn does not occur on the specified date or dusk on the following day
-
astral.sun.
twilight
(observer: astral.Observer, date: Optional[datetime.date] = None, direction: astral.SunDirection = <SunDirection.RISING: 1>, tzinfo: datetime.tzinfo = <UTC>) → Tuple[datetime.datetime, datetime.datetime]¶ Returns the start and end times of Twilight when the sun is traversing in the specified direction.
This method defines twilight as being between the time when the sun is at -6 degrees and sunrise/sunset.
Parameters: - observer – Observer to calculate twilight for
- date – Date for which to calculate the times. Default is today’s date in the timezone tzinfo.
- direction – Determines whether the time is for the sun rising or setting.
Use
astral.SunDirection.RISING
orastral.SunDirection.SETTING
. - tzinfo – Timezone to return times in. Default is UTC.
Returns: A tuple of the date and time at which twilight starts and ends.
Raises: ValueError
– if the sun does not rise or does not set
-
astral.sun.
blue_hour
(observer: astral.Observer, date: Optional[datetime.date] = None, direction: astral.SunDirection = <SunDirection.RISING: 1>, tzinfo: datetime.tzinfo = <UTC>) → Tuple[datetime.datetime, datetime.datetime]¶ Returns the start and end times of the Blue Hour when the sun is traversing in the specified direction.
This method uses the definition from PhotoPills i.e. the blue hour is when the sun is between 6 and 4 degrees below the horizon.
Parameters: - observer – Observer to calculate the blue hour for
- date – Date for which to calculate the times. Default is today’s date in the timezone tzinfo.
- direction – Determines whether the time is for the sun rising or setting.
Use
SunDirection.RISING
orSunDirection.SETTING
. - tzinfo – Timezone to return times in. Default is UTC.
Returns: A tuple of the date and time at which the Blue Hour starts and ends.
Raises: ValueError
– if the sun does not transit the elevations -4 & -6 degrees
-
astral.sun.
golden_hour
(observer: astral.Observer, date: Optional[datetime.date] = None, direction: astral.SunDirection = <SunDirection.RISING: 1>, tzinfo: datetime.tzinfo = <UTC>) → Tuple[datetime.datetime, datetime.datetime]¶ Returns the start and end times of the Golden Hour when the sun is traversing in the specified direction.
This method uses the definition from PhotoPills i.e. the golden hour is when the sun is between 4 degrees below the horizon and 6 degrees above.
Parameters: - observer – Observer to calculate the golden hour for
- date – Date for which to calculate the times. Default is today’s date in the timezone tzinfo.
- direction – Determines whether the time is for the sun rising or setting.
Use
SunDirection.RISING
orSunDirection.SETTING
. - tzinfo – Timezone to return times in. Default is UTC.
Returns: A tuple of the date and time at which the Golden Hour starts and ends.
Raises: ValueError
– if the sun does not transit the elevations -4 & +6 degrees
-
astral.sun.
rahukaalam
(observer: astral.Observer, date: Optional[datetime.date] = None, daytime: bool = True, tzinfo: datetime.tzinfo = <UTC>) → Tuple[datetime.datetime, datetime.datetime]¶ Calculate ruhakaalam times.
Parameters: - observer – Observer to calculate rahukaalam for
- date – Date to calculate for. Default is today’s date in the timezone tzinfo.
- daytime – If True calculate for the day time else calculate for the night time.
- tzinfo – Timezone to return times in. Default is UTC.
Returns: Tuple containing the start and end times for Rahukaalam.
Raises: ValueError
– if the sun does not rise or does not set
-
astral.sun.
zenith
(observer: astral.Observer, dateandtime: Optional[datetime.datetime] = None, with_refraction: bool = True) → float¶ Calculate the zenith angle of the sun.
Parameters: - observer – Observer to calculate the solar zenith for
- dateandtime – The date and time for which to calculate the angle. If dateandtime is None or is a naive Python datetime then it is assumed to be in the UTC timezone.
- with_refraction – If True adjust zenith to take refraction into account
Returns: The zenith angle in degrees.
-
astral.sun.
azimuth
(observer: astral.Observer, dateandtime: Optional[datetime.datetime] = None) → float¶ Calculate the azimuth angle of the sun.
Parameters: - observer – Observer to calculate the solar azimuth for
- dateandtime – The date and time for which to calculate the angle. If dateandtime is None or is a naive Python datetime then it is assumed to be in the UTC timezone.
Returns: The azimuth angle in degrees clockwise from North.
If dateandtime is a naive Python datetime then it is assumed to be in the UTC timezone.
-
astral.sun.
elevation
(observer: astral.Observer, dateandtime: Optional[datetime.datetime] = None, with_refraction: bool = True) → float¶ Calculate the sun’s angle of elevation.
Parameters: - observer – Observer to calculate the solar elevation for
- dateandtime – The date and time for which to calculate the angle. If dateandtime is None or is a naive Python datetime then it is assumed to be in the UTC timezone.
- with_refraction – If True adjust elevation to take refraction into account
Returns: The elevation angle in degrees above the horizon.
-
astral.sun.
time_at_elevation
(observer: astral.Observer, elevation: float, date: Optional[datetime.date] = None, direction: astral.SunDirection = <SunDirection.RISING: 1>, tzinfo: datetime.tzinfo = <UTC>) → datetime.datetime¶ Calculates the time when the sun is at the specified elevation on the specified date.
Note
This method uses positive elevations for those above the horizon.
Elevations greater than 90 degrees are converted to a setting sun i.e. an elevation of 110 will calculate a setting sun at 70 degrees.
Parameters: - elevation – Elevation of the sun in degrees above the horizon to calculate for.
- observer – Observer to calculate for
- date – Date to calculate for. Default is today’s date in the timezone tzinfo.
- direction – Determines whether the calculated time is for the sun rising or setting.
Use
SunDirection.RISING
orSunDirection.SETTING
. Default is rising. - tzinfo – Timezone to return times in. Default is UTC.
Returns: Date and time at which the sun is at the specified elevation.
astral.moon¶
-
astral.moon.
phase
(date: Optional[datetime.date] = None) → float¶ Calculates the phase of the moon on the specified date.
Parameters: date – The date to calculate the phase for. Dates are always in the UTC timezone. If not specified then today’s date is used. Returns: A number designating the phase. 0 .. 6.99 New moon 7 .. 13.99 First quarter 14 .. 20.99 Full moon 21 .. 27.99 Last quarter
astral.geocoder¶
Astral geocoder is a database of locations stored within the package.
To get the LocationInfo
for a location use the
lookup()
function e.g.
from astral.geocoder import lookup, database
l = lookup("London", database())
All locations stored in the database can be accessed using the all_locations generator
from astral.geocoder import all_locations
for location in all_locations:
print(location)
-
astral.geocoder.
lookup
(name: str, db: Dict[str, Dict[str, List[astral.LocationInfo]]]) → Union[Dict[KT, VT], astral.LocationInfo]¶ Look up a name in a database.
If a group with the name specified is a group name then that will be returned. If no group is found a location with the name will be looked up.
Parameters: - name – The group/location name to look up
- db – The location database to look in
Raises: KeyError
– if the name is not found
-
astral.geocoder.
database
() → Dict[str, Dict[str, List[astral.LocationInfo]]]¶ Returns a database populated with the inital set of locations stored in this module
-
astral.geocoder.
add_locations
(locations: Union[List[T], str], db: Dict[str, Dict[str, List[astral.LocationInfo]]]) → None¶ Add locations to the database.
Locations can be added by passing either a string with one line per location or by passing a list containing strings, lists or tuples (lists and tuples are passed directly to the LocationInfo constructor).
-
astral.geocoder.
all_locations
(db: Dict[str, Dict[str, List[astral.LocationInfo]]]) → Generator[astral.LocationInfo, None, None]¶ A generator that returns all the
LocationInfo
s contained in the database
astral.location¶
-
class
astral.location.
Location
(info: Optional[astral.LocationInfo] = None)¶ Provides access to information for single location.
-
blue_hour
(direction: astral.SunDirection = <SunDirection.RISING: 1>, date: datetime.date = None, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → Tuple[datetime.datetime, datetime.datetime]¶ Returns the start and end times of the Blue Hour when the sun is traversing in the specified direction.
This method uses the definition from PhotoPills i.e. the blue hour is when the sun is between 6 and 4 degrees below the horizon.
Parameters: - direction – Determines whether the time is for the sun rising or setting.
Use
SunDirection.RISING
orSunDirection.SETTING
. Default is rising. - date – The date for which to calculate the times. If no date is specified then the current date will be used.
- local – True = Times to be returned in location’s time zone; False = Times to be returned in UTC. If not specified then the time will be returned in local time
- observer_elevation – Elevation of the observer in metres above the location.
Returns: A tuple of the date and time at which the Blue Hour starts and ends.
- direction – Determines whether the time is for the sun rising or setting.
Use
-
dawn
(date: datetime.date = None, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → datetime.datetime¶ Calculates the time in the morning when the sun is a certain number of degrees below the horizon. By default this is 6 degrees but can be changed by setting the
Astral.solar_depression
property.Parameters: - date – The date for which to calculate the dawn time. If no date is specified then the current date will be used.
- local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
- observer_elevation – Elevation of the observer in metres above the location.
Returns: The date and time at which dawn occurs.
-
daylight
(date: datetime.date = None, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → Tuple[datetime.datetime, datetime.datetime]¶ Calculates the daylight time (the time between sunrise and sunset)
Parameters: - date – The date for which to calculate daylight. If no date is specified then the current date will be used.
- local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
- observer_elevation – Elevation of the observer in metres above the location.
Returns: A tuple containing the start and end times
-
dusk
(date: datetime.date = None, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → datetime.datetime¶ Calculates the dusk time (the time in the evening when the sun is a certain number of degrees below the horizon. By default this is 6 degrees but can be changed by setting the
solar_depression
property.)Parameters: - date – The date for which to calculate the dusk time. If no date is specified then the current date will be used.
- local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
- observer_elevation – Elevation of the observer in metres above the location.
Returns: The date and time at which dusk occurs.
-
golden_hour
(direction: astral.SunDirection = <SunDirection.RISING: 1>, date: datetime.date = None, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → Tuple[datetime.datetime, datetime.datetime]¶ Returns the start and end times of the Golden Hour when the sun is traversing in the specified direction.
This method uses the definition from PhotoPills i.e. the golden hour is when the sun is between 4 degrees below the horizon and 6 degrees above.
Parameters: - direction – Determines whether the time is for the sun rising or setting.
Use
SunDirection.RISING
orSunDirection.SETTING
. Default is rising. - date – The date for which to calculate the times.
- local – True = Times to be returned in location’s time zone; False = Times to be returned in UTC. If not specified then the time will be returned in local time
- observer_elevation – Elevation of the observer in metres above the location.
Returns: A tuple of the date and time at which the Golden Hour starts and ends.
- direction – Determines whether the time is for the sun rising or setting.
Use
-
latitude
¶ The location’s latitude
latitude
can be set either as a string or as a numberFor strings they must be of the form
degrees°minutes’[N|S] e.g. 51°31’NFor numbers, positive numbers signify latitudes to the North.
-
longitude
¶ The location’s longitude.
longitude
can be set either as a string or as a numberFor strings they must be of the form
degrees°minutes’[E|W] e.g. 51°31’WFor numbers, positive numbers signify longitudes to the East.
-
midnight
(date: datetime.date = None, local: bool = True) → datetime.datetime¶ Calculates the solar midnight (the time when the sun is at its lowest point.)
Parameters: - date – The date for which to calculate the midnight time. If no date is specified then the current date will be used.
- local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
Returns: The date and time at which the solar midnight occurs.
-
moon_phase
(date: datetime.date = None, local: bool = True)¶ Calculates the moon phase for a specific date.
Parameters: date – The date to calculate the phase for. If ommitted the current date is used. Returns: A number designating the phase 0 .. 6.99 New moon 7 .. 13.99 First quarter 14 .. 20.99 Full moon 21 .. 27.99 Last quarter
-
night
(date: datetime.date = None, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → Tuple[datetime.datetime, datetime.datetime]¶ Calculates the night time (the time between astronomical dusk and astronomical dawn of the next day)
Parameters: - date – The date for which to calculate the start of the night time. If no date is specified then the current date will be used.
- local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
- observer_elevation – Elevation of the observer in metres above the location.
Returns: A tuple containing the start and end times
-
noon
(date: datetime.date = None, local: bool = True) → datetime.datetime¶ Calculates the solar noon (the time when the sun is at its highest point.)
Parameters: - date – The date for which to calculate the noon time. If no date is specified then the current date will be used.
- local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
Returns: The date and time at which the solar noon occurs.
-
rahukaalam
(date: datetime.date = None, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → Tuple[datetime.datetime, datetime.datetime]¶ Calculates the period of rahukaalam.
Parameters: - date – The date for which to calculate the rahukaalam period.
A value of
None
uses the current date. - local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC.
- observer_elevation – Elevation of the observer in metres above the location.
Returns: Tuple containing the start and end times for Rahukaalam.
- date – The date for which to calculate the rahukaalam period.
A value of
-
solar_azimuth
(dateandtime: datetime.datetime = None, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → float¶ Calculates the solar azimuth angle for a specific date/time.
Parameters: dateandtime – The date and time for which to calculate the angle. Returns: The azimuth angle in degrees clockwise from North.
-
solar_depression
¶ The number of degrees the sun must be below the horizon for the dawn/dusk calculation.
Can either be set as a number of degrees below the horizon or as one of the following strings
String Degrees civil 6.0 nautical 12.0 astronomical 18.0
-
solar_elevation
(dateandtime: datetime.datetime = None, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → float¶ Calculates the solar elevation angle for a specific time.
Parameters: dateandtime – The date and time for which to calculate the angle. Returns: The elevation angle in degrees above the horizon.
-
solar_zenith
(dateandtime: datetime.datetime, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → float¶ Calculates the solar zenith angle for a specific time.
Parameters: dateandtime – The date and time for which to calculate the angle. Returns: The zenith angle in degrees from vertical.
-
sun
(date: datetime.date = None, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → dict¶ Returns dawn, sunrise, noon, sunset and dusk as a dictionary.
Parameters: - date – The date for which to calculate the times. If no date is specified then the current date will be used.
- local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
- observer_elevation – Elevation of the observer in metres above the location.
Returns: Dictionary with keys
dawn
,sunrise
,noon
,sunset
anddusk
whose values are the results of the corresponding methods.
-
sunrise
(date: datetime.date = None, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → datetime.datetime¶ Return sunrise time.
Calculates the time in the morning when the sun is a 0.833 degrees below the horizon. This is to account for refraction.
Parameters: - date – The date for which to calculate the sunrise time. If no date is specified then the current date will be used.
- local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
- observer_elevation – Elevation of the observer in metres above the location.
Returns: The date and time at which sunrise occurs.
-
sunset
(date: datetime.date = None, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0) → datetime.datetime¶ Calculates sunset time (the time in the evening when the sun is a 0.833 degrees below the horizon. This is to account for refraction.)
Parameters: - date – The date for which to calculate the sunset time. If no date is specified then the current date will be used.
- local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
- observer_elevation – Elevation of the observer in metres above the location.
Returns: The date and time at which sunset occurs.
-
time_at_elevation
(elevation: float, date: datetime.date = None, direction: astral.SunDirection = <SunDirection.RISING: 1>, local: bool = True) → datetime.datetime¶ Calculate the time when the sun is at the specified elevation.
Note
This method uses positive elevations for those above the horizon.
Elevations greater than 90 degrees are converted to a setting sun i.e. an elevation of 110 will calculate a setting sun at 70 degrees.
Parameters: - elevation – Elevation in degrees above the horizon to calculate for.
- date – The date for which to calculate the elevation time. If no date is specified then the current date will be used.
- direction – Determines whether the time is for the sun rising or setting.
Use
SunDirection.RISING
orSunDirection.SETTING
. Default is rising. - local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
Returns: The date and time at which dusk occurs.
-
timezone
¶ The name of the time zone for the location.
A list of time zone names can be obtained from pytz. For example.
>>> from pytz import all_timezones >>> for timezone in all_timezones: ... print(timezone)
-
twilight
(date: datetime.date = None, direction: astral.SunDirection = <SunDirection.RISING: 1>, local: bool = True, observer_elevation: Union[float, Tuple[float, float]] = 0.0)¶ Returns the start and end times of Twilight in the UTC timezone when the sun is traversing in the specified direction.
This method defines twilight as being between the time when the sun is at -6 degrees and sunrise/sunset.
Parameters: - direction – Determines whether the time is for the sun rising or setting.
Use
astral.SUN_RISING
orastral.SunDirection.SETTING
. - date – The date for which to calculate the times.
- local – True = Time to be returned in location’s time zone; False = Time to be returned in UTC. If not specified then the time will be returned in local time
- observer_elevation – Elevation of the observer in metres above the location.
Returns: A tuple of the UTC date and time at which twilight starts and ends.
- direction – Determines whether the time is for the sun rising or setting.
Use
-
tz
¶ Time zone information.
-
tzinfo
¶ Time zone information.
-