Python calculations for the position of the sun and moon.

Overview

Astral

travis_status pypi_ver

This is 'astral' a Python module which calculates

  • Times for various positions of the sun: dawn, sunrise, solar noon, sunset, dusk, solar elevation, solar azimuth and rahukaalam.
  • The phase of the moon.

For documentation see the https://astral.readthedocs.io/en/latest/index.html

Comments
  • Weird moon phase calculations, float return value does not seem to work

    Weird moon phase calculations, float return value does not seem to work

    Thanks for the effort, astral is a great piece of work,very much appreciated. I did some calculations with it and compared the results with some diaries one can buy in bookshops as well as with moon phases calendar, such as this one: https://www.timeanddate.com/moon/phases/?year=2019 They all agree and slightly disagree with astral's calculations, sometimes there is a shift, always max. 1 day compared with the others. I've also observed it yields the very same moon age for two consecutive calendar days before such a skew happens, so I guess it is because of the integer return value of the moon phase. Tried to go for float return value but no matter what I pass for rtype, I always get int.

    opened by princzp 5
  • Lookup of moon phase name

    Lookup of moon phase name

    Please add a lookup of the moon phase name.

    A suggestion of doing this is by returning a string for a float value:

    • phase < 1 returns New moon
    • phase >= 1 and phase < 7 returns Waxing crescent
    • phase >= 7 and phase < 8 returns First quarter
    • phase >= 8 and phase < 14 returns Waxing gibbous
    • phase >= 14 and phase < 15 returns Full moon
    • phase >= 15 and phase < 21 returns Waning gibbous
    • phase >= 21 and phase < 22 returns Last quarter
    • phase >= 22 returns Waning crescent
    • the rest returns an empty string

    Implementation should support localization of the names via gettext. Implementation could even be in exiting method moon_phase() when rtype=str.

    PS The exact values above should be reviewed by someone with more in-depth knowledge of this subject.

    opened by PanderMusubi 5
  • Feature request: Calculate Moon rise and set times

    Feature request: Calculate Moon rise and set times

    It would be helpful if Astral could be used to calculate moon rise and set times in addition to phase of the moon.

    I'm hoping this would be somewhat in scope for Astral since it is already calculating moon phase.

    Support for moon rise and set would be useful in projects like Home Assistant that use Astral.

    • https://community.home-assistant.io/t/moon-rise-set/50896
    opened by rct 4
  • Sun Calculations for Custom Location Wrong

    Sun Calculations for Custom Location Wrong

    Using the example at https://astral.readthedocs.io/en/latest/ when I put my latitude and longitude in the returned times are completely off.

    `#!/usr/bin/python3

    import datetime from astral.sun import sun from astral import LocationInfo from astral.location import Location city = LocationInfo("London", "England", "Europe/London", 51.5, -0.116) pbmo = LocationInfo("Poplar Bluff", "Midwest", "US/Central", 36.873512, -90.488008)

    print(( f"Information for {city.name}/{city.region}\n" f"Timezone: {city.timezone}\n" f"Latitude: {city.latitude:.02f}; Longitude: {city.longitude:.02f}\n" ))

    s = sun(city.observer, date=datetime.date(2020, 2, 11)) print(( f'Dawn: {s["dawn"]}\n' f'Sunrise: {s["sunrise"]}\n' f'Noon: {s["noon"]}\n' f'Sunset: {s["sunset"]}\n' f'Dusk: {s["dusk"]}\n' ))

    print(( f"Information for {pbmo.name}/{pbmo.region}\n" f"Timezone: {pbmo.timezone}\n" f"Latitude: {pbmo.latitude:.02f}; Longitude: {pbmo.longitude:.02f}\n" ))

    s = sun(pbmo.observer, date=datetime.date(2020, 2, 11)) print(( f'Dawn: {s["dawn"]}\n' f'Sunrise: {s["sunrise"]}\n' f'Noon: {s["noon"]}\n' f'Sunset: {s["sunset"]}\n' f'Dusk: {s["dusk"]}\n' )) Running this results in:[email protected]:~/gitlocal/coop2$ ./sun2.py Information for London/England Timezone: Europe/London Latitude: 51.50; Longitude: -0.12

    Dawn: 2020-02-11 06:47:32.053221+00:00 Sunrise: 2020-02-11 07:23:12.648323+00:00 Noon: 2020-02-11 12:14:41+00:00 Sunset: 2020-02-11 17:06:54.384574+00:00 Dusk: 2020-02-11 17:42:38.338837+00:00

    Information for Poplar Bluff/Midwest Timezone: US/Central Latitude: 36.87; Longitude: -90.49

    Dawn: 2020-02-11 12:28:12.640188+00:00 Sunrise: 2020-02-11 12:55:27.838617+00:00 Noon: 2020-02-11 18:16:10+00:00 Sunset: 2020-02-11 23:37:22.438327+00:00 Dusk: 2020-02-12 00:04:38.943368+00:00 `

    Thanks for Astral, I've been using it in my current chicken coop to open and close the door for a couple of years now. Just upgrading the new coop to Python 3 and Astral 2.

    JT

    opened by jethornton 4
  • GPG signatures for source validation

    GPG signatures for source validation

    As we all know, today more than ever before, it is crucial to be able to trust our computing environments. One of the main difficulties that package maintainers of GNU/Linux distributions face, is the difficulty to verify the authenticity and the integrity of the source code. With GPG signatures it is possible for packagers to verify source code releases quickly and easily.

    Overview of the required tasks:

    GPGit

    GPGit is meant to bring GPG to the masses. It is not only a Python script that automates the process of creating new signed Git releases with GPG, but also a quick-start-guide for learning how to use GPG. GPGit integrates perfectly with the Github Release API for uploading.

    The security status of GNU/Linux projects will be tracked in the Linux Security Database. If you have any further questions, do not hesitate to contact me personally. Thanks for your help in making GNU/Linux projects more secure by using GPG signatures.

    Thanks in advance.

    opened by NicoHood 3
  • hard paths in setup.cfg breaks install under buildout

    hard paths in setup.cfg breaks install under buildout

    Hard coding paths in your setup.cfg breaks installing under buildout.

    It's also surprising when using simple python setup.py build If build attempted higher in the file system, they could try to write in / (or above!).

    Suggest you remove those lines from prod distributions.

    opened by dotnetslash 3
  • Help with Timezone

    Help with Timezone

    Hi, I'm upgrading my program from v1.6 to v2.1. I've notice since the clocks have changed in the U.K. that the time is off by one hour. I think it is the same as (closed) issue #29, but I cannot get this to work. Here is the code I've been using:

    from datetime import date from datetime import timedelta # Automatically handle day that span over the month

    from astral import LocationInfo from astral.sun import sun

    city = LocationInfo('Headley', 'England', 'Europe/London', 51.1211, -0.8297)

    today = date.today() print(today)

    for x in range(0, 7): day = sun(city.observer, today) print('Dusk: %s' % str(day['dusk'])) print('Dawn: %s' % str(day['dawn'])) today += timedelta(days=1)

    Also have the calculations changed between version as irrespective of the hour difference, the times are different by a few minutes. Any help would be appreciated.

    opened by Badger101 2
  • How to extract solar elevation and solar noon in high latitude sites?

    How to extract solar elevation and solar noon in high latitude sites?

    I think this issue is different from, but relates to, issues 9 and 34.

    I need to compute solar elevation and solar noon for a high latitude location (lat = 70, long= -139), but calling sun (as per the documentation) returns the error "ValueError: Sun never reaches 6.0 degrees below the horizon, at this location". That statement is correct in the summer, but solar noon does happen and there is a solar elevation at that time.

    Is there any way to compute just these parameters using astral?

    opened by AndrewCunliffe 2
  • Sun calculation not working correctly for NZ?

    Sun calculation not working correctly for NZ? "Sun never transits at a zenith of 96.0 on 2020-02-11"

    I'm getting this error with astral==2.0.1 (also with the 2.0.2 tag, and with latest master 60aa65f79a442be03d292fe2b874aa420d27b497) when trying to calculate sun data from NZ:

    "ValueError: Sun never transits at a zenith of 96.0 on 2020-02-11"

    Example:

    from astral.geocoder import database, lookup
    from astral.sun import sun
    import pprint
    
    london = lookup("London", database())
    pprint.pprint(sun(london.observer))
    

    outputs something reasonable:

    {'dawn': datetime.datetime(2020, 2, 11, 6, 47, 1, 656555, tzinfo=<UTC>),
     'dusk': datetime.datetime(2020, 2, 11, 17, 42, 13, 415600, tzinfo=<UTC>),
     'noon': datetime.datetime(2020, 2, 11, 12, 14, 14, tzinfo=<UTC>),
     'sunrise': datetime.datetime(2020, 2, 11, 7, 22, 40, 881412, tzinfo=<UTC>),
     'sunset': datetime.datetime(2020, 2, 11, 17, 6, 30, 837342, tzinfo=<UTC>)}
    
    wellington = lookup("Wellington", database())
    pprint.pprint(sun(wellington.observer))
    

    hits this exception

    Traceback (most recent call last):
      File "/home/johnc/.PyCharm2019.3/config/scratches/scratch_10.py", line 11, in <module>
        pprint.pprint(sun(wellington.observer))
      File "/home/johnc/.virtualenvs/sureflap_gcloud/lib/python3.7/site-packages/astral/sun.py", line 1123, in sun
        "dawn": dawn(observer, date, dawn_dusk_depression, tzinfo),
      File "/home/johnc/.virtualenvs/sureflap_gcloud/lib/python3.7/site-packages/astral/sun.py", line 738, in dawn
        observer, date, 90.0 + dep, SunDirection.RISING
      File "/home/johnc/.virtualenvs/sureflap_gcloud/lib/python3.7/site-packages/astral/sun.py", line 380, in time_of_transit
        raise ValueError(f"Sun never transits at a zenith of {zenith} on {date}")
    ValueError: Sun never transits at a zenith of 96.0 on 2020-02-11
    
    released 
    opened by therefromhere 2
  • Current date doesn't take timezone into account

    Current date doesn't take timezone into account

    Location.sun etc will default to the system date if it's not specified. I think it should take tz into account if local=True?

    I hit this issue today in NZ, where the clocks just changed. Calculated dawn (etc) was off by 1 hour since the machine tz wasn't the same the location tz, therefore this morning the date was defaulting to yesterday, and therefore wasn't using daylight saving.

    opened by therefromhere 2
  • Tag new release

    Tag new release

    Hi, I try to build astral for archlinux and got some problems with the recent 1.4.1 tag. You've fixed those issues in the master branch, it would be nice if you could update those.

    The issue is the missing setup.cfg which is loaded by version=versioneer.get_version(), and other parts in the setup. Maybe you can just tag a release 1.4.2 (also gpg signed? #10 )

    opened by NicoHood 2
  • Missing sunsets for arctic circle locations

    Missing sunsets for arctic circle locations

    Hi, I'm trying to use this library for calculating sunrises and sunsets, but finding several missing data points when looking at Arctic locations. All times are in UTC

    My test cases are Kap Morris Jessup, Greenland and Tromso, Norway.
    location = LocationInfo('Kap Morris Jessup', 'Greenland', 'UTC', lat=83.6561, long=-33.3739 ) location = LocationInfo('Tromso', 'Norway', 'UTC', lat=69.6492,long=18.9553 )

    Kap Morris Jessup: The data for 8th-12th September 2022 can be viewed at the USNO site https://aa.usno.navy.mil/calculated/rstt/year?ID=AA&year=2022&task=0&lat=83.6561&lon=-33.3739&label=Kap+Morris+Jessup&tz=0.00&tz_sign=-1&submit=Get+Data

    Notably in this date range there is a sunset on the 9th and two sunsets on the 11th. yielding the following data : "sunsets": [ "2022-09-09T01:24:00Z", "2022-09-10T00:39:00Z", "2022-09-11T00:08:00Z", "2022-09-11T23:44:00Z", "2022-09-12T23:22:00Z" ]

    However Astral is giving only the following sunsets (missing a sunset on the 9th and 11th): sunsets=[ '2022-09-10T00:34:00Z', '2022-09-11T23:41:00Z', '2022-09-12T23:19:00Z' ]

    Same for Tromso 14-20 May 2020 with sunrises: sunrises=['2023-05-12T00:13:00Z', '2023-05-13T00:04:00Z', '2023-05-13T23:56:00Z', '2023-05-14T23:46:00Z', '2023-05-15T23:35:00Z', '2023-05-16T23:22:00Z' ] vs Astral sunrises=[ '2023-05-15T01:46:00Z', '2023-05-16T01:35:00Z', '2023-05-17T01:27:00Z' ]

    Is sunrise / sunset not usable for arctic locations?

    opened by DaleShipp 0
  • Sunset times returning for previous day

    Sunset times returning for previous day

    Since astral 2.2, computing the sunset time appears to be return the time for the previous day. More accurately, if the sunset time ends up being UTC the next day, the day component of the date isn't changed. For example... Jul 10,2022 for my location sunset returns as Jul 10, 2022 03:10 UTC. I'm in the -7:00 timezone, so that would mean sunset for July 10 was computed as July 9 20;10. Clearly sunset on July 10 couldn't start the day before. I think the day component of the time should have been 11, not 10.

    This code replicates the issue. On astral 3.0, 3.1 and 3,2 it returns datetime.datetime(2022, 7, 10, 3, 10, 4, 552844, tzinfo=datetime.timezone.utc) On astral 2.2 it returns datetime.datetime(2022, 7, 11, 3, 9, 47, 57594, tzinfo=<UTC>)

    I believe the return value from astral 2.2 is the correct value.

    import datetime
    import astral
    from astral.sun import sunset
    
    ob = astral.Observer(latitude=34.175301, longitude=-118.983334, elevation=0.0)
    sunset(ob, date=datetime.date(2022, 7, 10))
    

    I'm open to the possibility I'm doing it wrong, but I didn't see anything in release notes that said I needed to change anything. Noticed this when upgrading from Astral 2.2 to 3.2 -- previously working code began to fail.

    Thanks for any help / insights!

    opened by erichorne 0
  • Sun rise and set cal error

    Sun rise and set cal error

    Sunset and sunrise calculations occurred error

    The code are below:

        day = datetime.date(2024, 3, 22)
        lat = 38.41129869
        lon =  90.137575
        city = LocationInfo('name', 'region', 'timezone/name', lat, lon)
        try:
            s = sun(city.observer, day, tzinfo=timezone(timedelta(hours=8)))
            r = {}
            r.update({'sunset': s['sunset'].replace(tzinfo=None),
                      'sunrise': s['sunrise'].replace(tzinfo=None), })
        except ValueError as e:
            logger.exception(e)
    
    

    The error

    ValueError: Unable to find a sunrise time on the date specified
    

    Other parameters also have this error, like:

    day,lat,lon
    2028-04-07,44.6072919,82.894195
    2013-03-05,36.38176111,96.44025556
    2010-04-16,41.17189303,80.25687664
    2011-04-29,39.714734,76.167327
    2018-01-20,39.16666666,109.05
    
    opened by Water-Ghost 0
  • Sunrise time calculation error

    Sunrise time calculation error

    version 3.2

    I used latitude 39.3528 and longitude 106.7333 to calculate the sunrise and sunset times for the whole year of 2015, starting on February 3, 2015, the calculated sunrise time was later than the sunset time, and this was the case until December 7, 2015.

    my code:

    lat_station_val = 39.35277777777778
    lon_station_val = 106.73333333333333
    
    location_staion9 = LocationInfo('shizuishan','china','Asia/Shanghai',lat_station_val,lon_station_val)
    
    data_file = open("result.csv", 'w') 
    data_file.write("date,sunrise,sunset\n")
    
    start_date = date(2015, 1, 1)
    for i in range(0,365):
        delta=timedelta(days=i)
        cal_date = start_date + delta
    
        s = sun(location_staion9.observer, date=cal_date)
        utc_sunrise = s["sunrise"]
        utc_sunset = s["sunset"]
    
        data_file.write("{},{},{}\n".format(cal_date.strftime('%Y-%m-%d'), utc_sunrise.strftime('%Y-%m-%d %H:%M:%S'), utc_sunset.strftime('%Y-%m-%d %H:%M:%S')))
    

    the result:

    2015-01-28,2015-01-28 00:04:28,2015-01-28 10:07:44
    2015-01-29,2015-01-29 00:03:41,2015-01-29 10:08:55
    2015-01-30,2015-01-30 00:02:52,2015-01-30 10:10:06
    2015-01-31,2015-01-31 00:02:01,2015-01-31 10:11:16
    2015-02-01,2015-02-01 00:01:08,2015-02-01 10:12:27
    2015-02-02,2015-02-02 00:00:14,2015-02-02 10:13:38
    **2015-02-03,2015-02-03 23:58:20,2015-02-03 10:14:49**
    2015-02-04,2015-02-04 23:57:21,2015-02-04 10:16:00
    2015-02-05,2015-02-05 23:56:20,2015-02-05 10:17:11
    2015-02-06,2015-02-06 23:55:18,2015-02-06 10:18:21
    2015-02-07,2015-02-07 23:54:14,2015-02-07 10:19:32
    2015-02-08,2015-02-08 23:53:09,2015-02-08 10:20:42
    2015-02-09,2015-02-09 23:52:02,2015-02-09 10:21:53
    2015-02-10,2015-02-10 23:50:54,2015-02-10 10:23:03
    2015-02-11,2015-02-11 23:49:45,2015-02-11 10:24:13
    
    opened by tz850 0
  • Moon culminant/noon

    Moon culminant/noon

    Is there a way to calculate at what time the moon reaches its highest point on the sky, after rising? [the moon culminant point, noon]. I looked through the documentation and found nothing on this.

    Thank you .

    Best regards, Marius.

    opened by marius-sucan 0
  • Mypy flags comment as invalid

    Mypy flags comment as invalid

    Hi! Not here to nag you or ask for features, just wanted to ask if this error also occurs to the developers here when you run mypy against atral's code: /astral/sun.py:450: error: Invalid "type: ignore" comment

    Running mypy="0.971" and astral="^3.1". Thanks! https://github.com/sffjunkie/astral/blob/b805285654948c6513f378952aab685085efbad6/src/astral/sun.py#L447

    opened by DavidFreire-FEUP 1
Releases(3.0)
Owner
Simon Kennedy
PGP Fingerprint: BEC3 E77B FAF6 4A14 498B 8BEF BB47 9E42 77CE 4DD0
Simon Kennedy
Evaluation toolkit of the informative tracking benchmark comprising 9 scenarios, 180 diverse videos, and new challenges.

Informative-tracking-benchmark Informative tracking benchmark (ITB) higher diversity. It contains 9 representative scenarios and 180 diverse videos. m

Xin Li 15 Nov 26, 2022
git《Self-Attention Attribution: Interpreting Information Interactions Inside Transformer》(AAAI 2021) GitHub:

Self-Attention Attribution This repository contains the implementation for AAAI-2021 paper Self-Attention Attribution: Interpreting Information Intera

60 Dec 29, 2022
The code uses SegFormer for Semantic Segmentation on Drone Dataset.

SegFormer_Segmentation The code uses SegFormer for Semantic Segmentation on Drone Dataset. The details for the SegFormer can be obtained from the foll

Dr. Sander Ali Khowaja 1 May 08, 2022
Jingju baseline - A baseline model of our project of Beijing opera script generation

Jingju Baseline It is a baseline of our project about Beijing opera script gener

midon 1 Jan 14, 2022
Hyperbolic Image Segmentation, CVPR 2022

Hyperbolic Image Segmentation, CVPR 2022 This is the implementation of paper Hyperbolic Image Segmentation (CVPR 2022). Repository structure assets :

Mina Ghadimi Atigh 46 Dec 29, 2022
The sixth place winning solution (6/220) in 2021 Gaofen Challenge.

SwinTransformer + OBBDet The sixth place winning solution (6/220) in the track of Fine-grained Object Recognition in High-Resolution Optical Images, 2

ming71 46 Dec 02, 2022
Benchmark for Answering Existential First Order Queries with Single Free Variable

EFO-1-QA Benchmark for First Order Query Estimation on Knowledge Graphs This repository contains an entire pipeline for the EFO-1-QA benchmark. EFO-1

HKUST-KnowComp 14 Oct 24, 2022
Sharpness-Aware Minimization for Efficiently Improving Generalization

Sharpness-Aware-Minimization-TensorFlow This repository provides a minimal implementation of sharpness-aware minimization (SAM) (Sharpness-Aware Minim

Sayak Paul 54 Dec 08, 2022
Anagram Generator in Python

Anagrams Generator This is a program for computing multiword anagrams. It makes no effort to come up with sentences that make sense; it only finds ana

Day Fundora 5 Nov 17, 2022
Nerf pl - NeRF (Neural Radiance Fields) and NeRF in the Wild using pytorch-lightning

nerf_pl Update: an improved NSFF implementation to handle dynamic scene is open! Update: NeRF-W (NeRF in the Wild) implementation is added to nerfw br

AI葵 1.8k Dec 30, 2022
AI Summer's complete catalog of articles

Learn Deep Learning with AI Summer A collection of all articles (almost 100) written for the AI Summer blog organized by topic. Deep Learning Theory M

AI Summer 95 Dec 29, 2022
This repository contains the code used for Predicting Patient Outcomes with Graph Representation Learning (https://arxiv.org/abs/2101.03940).

Predicting Patient Outcomes with Graph Representation Learning This repository contains the code used for Predicting Patient Outcomes with Graph Repre

Emma Rocheteau 76 Dec 22, 2022
Optimising chemical reactions using machine learning

Summit Summit is a set of tools for optimising chemical processes. We’ve started by targeting reactions. What is Summit? Currently, reaction optimisat

Sustainable Reaction Engineering Group 75 Dec 14, 2022
A module for solving and visualizing Schrödinger equation.

qmsolve This is an attempt at making a solid, easy to use solver, capable of solving and visualize the Schrödinger equation for multiple particles, an

506 Dec 28, 2022
Export CenterPoint PonintPillars ONNX Model For TensorRT

CenterPoint-PonintPillars Pytroch model convert to ONNX and TensorRT Welcome to CenterPoint! This project is fork from tianweiy/CenterPoint. I impleme

CarkusL 149 Dec 13, 2022
Pytorch implementation of Masked Auto-Encoder

Masked Auto-Encoder (MAE) Pytorch implementation of Masked Auto-Encoder: Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, Ross Girshick

Jiyuan 22 Dec 13, 2022
This repository implements variational graph auto encoder by Thomas Kipf.

Variational Graph Auto-encoder in Pytorch This repository implements variational graph auto-encoder by Thomas Kipf. For details of the model, refer to

DaehanKim 215 Jan 02, 2023
The code for our CVPR paper PISE: Person Image Synthesis and Editing with Decoupled GAN, Project Page, supp.

PISE The code for our CVPR paper PISE: Person Image Synthesis and Editing with Decoupled GAN, Project Page, supp. Requirement conda create -n pise pyt

jinszhang 110 Nov 21, 2022
OpenMMLab Computer Vision Foundation

English | 简体中文 Introduction MMCV is a foundational library for computer vision research and supports many research projects as below: MMCV: OpenMMLab

OpenMMLab 4.6k Jan 09, 2023
An implementation for `Text2Event: Controllable Sequence-to-Structure Generation for End-to-end Event Extraction`

Text2Event An implementation for Text2Event: Controllable Sequence-to-Structure Generation for End-to-end Event Extraction Please contact Yaojie Lu (@

Roger 153 Jan 07, 2023