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
As a part of the HAKE project, includes the reproduced SOTA models and the corresponding HAKE-enhanced versions (CVPR2020).

HAKE-Action HAKE-Action (TensorFlow) is a project to open the SOTA action understanding studies based on our Human Activity Knowledge Engine. It inclu

Yong-Lu Li 94 Nov 18, 2022
An implementation of the research paper "Retina Blood Vessel Segmentation Using A U-Net Based Convolutional Neural Network"

Retina Blood Vessels Segmentation This is an implementation of the research paper "Retina Blood Vessel Segmentation Using A U-Net Based Convolutional

Srijarko Roy 23 Aug 20, 2022
Visualize Camera's Pose Using Extrinsic Parameter by Plotting Pyramid Model on 3D Space

extrinsic2pyramid Visualize Camera's Pose Using Extrinsic Parameter by Plotting Pyramid Model on 3D Space Intro A very simple and straightforward modu

JEONG HYEONJIN 106 Dec 28, 2022
A machine learning package for streaming data in Python. The other ancestor of River.

scikit-multiflow is a machine learning package for streaming data in Python. creme and scikit-multiflow are merging into a new project called River. W

670 Dec 30, 2022
Global Pooling, More than Meets the Eye: Position Information is Encoded Channel-Wise in CNNs, ICCV 2021

Global Pooling, More than Meets the Eye: Position Information is Encoded Channel-Wise in CNNs, ICCV 2021 Global Pooling, More than Meets the Eye: Posi

Md Amirul Islam 32 Apr 24, 2022
Large scale PTM - PPI relation extraction

Large-scale protein-protein post-translational modification extraction with distant supervision and confidence calibrated BioBERT The silver standard

1 Feb 25, 2022
An official source code for "Augmentation-Free Self-Supervised Learning on Graphs"

Augmentation-Free Self-Supervised Learning on Graphs An official source code for Augmentation-Free Self-Supervised Learning on Graphs paper, accepted

Namkyeong Lee 59 Dec 01, 2022
Co-GAIL: Learning Diverse Strategies for Human-Robot Collaboration

CoGAIL Table of Content Overview Installation Dataset Training Evaluation Trained Checkpoints Acknowledgement Citations License Overview This reposito

Jeremy Wang 29 Dec 24, 2022
Official implementation of the paper Do pedestrians pay attention? Eye contact detection for autonomous driving

Do pedestrians pay attention? Eye contact detection for autonomous driving Official implementation of the paper Do pedestrians pay attention? Eye cont

VITA lab at EPFL 26 Nov 02, 2022
PyTorch image models, scripts, pretrained weights -- ResNet, ResNeXT, EfficientNet, EfficientNetV2, NFNet, Vision Transformer, MixNet, MobileNet-V3/V2, RegNet, DPN, CSPNet, and more

PyTorch Image Models Sponsors What's New Introduction Models Features Results Getting Started (Documentation) Train, Validation, Inference Scripts Awe

Ross Wightman 22.9k Jan 09, 2023
A tool to visualise the results of AlphaFold2 and inspect the quality of structural predictions

AlphaFold Analyser This program produces high quality visualisations of predicted structures produced by AlphaFold. These visualisations allow the use

Oliver Powell 3 Nov 13, 2022
Image Captioning using CNN and Transformers

Image-Captioning Keras/Tensorflow Image Captioning application using CNN and Transformer as encoder/decoder. In particulary, the architecture consists

24 Dec 28, 2022
A JAX implementation of Broaden Your Views for Self-Supervised Video Learning, or BraVe for short.

BraVe This is a JAX implementation of Broaden Your Views for Self-Supervised Video Learning, or BraVe for short. The model provided in this package wa

DeepMind 44 Nov 20, 2022
Implementation of Diverse Semantic Image Synthesis via Probability Distribution Modeling

Diverse Semantic Image Synthesis via Probability Distribution Modeling (CVPR 2021) Paper Zhentao Tan, Menglei Chai, Dongdong Chen, Jing Liao, Qi Chu,

tzt 45 Nov 17, 2022
Official PyTorch Implementation of Learning Architectures for Binary Networks

Learning Architectures for Binary Networks An Pytorch Implementation of the paper Learning Architectures for Binary Networks (BNAS) (ECCV 2020) If you

Computer Vision Lab. @ GIST 25 Jun 09, 2022
An unofficial PyTorch implementation of a federated learning algorithm, FedAvg.

Federated Averaging (FedAvg) in PyTorch An unofficial implementation of FederatedAveraging (or FedAvg) algorithm proposed in the paper Communication-E

Seok-Ju Hahn 123 Jan 06, 2023
D2LV: A Data-Driven and Local-Verification Approach for Image Copy Detection

Facebook AI Image Similarity Challenge: Matching Track —— Team: imgFp This is the source code of our 3rd place solution to matching track of Image Sim

16 Dec 25, 2022
PyTorch code for ICLR 2021 paper Unbiased Teacher for Semi-Supervised Object Detection

Unbiased Teacher for Semi-Supervised Object Detection This is the PyTorch implementation of our paper: Unbiased Teacher for Semi-Supervised Object Detection

Facebook Research 366 Dec 28, 2022
Awesome-AI-books - Some awesome AI related books and pdfs for learning and downloading

Awesome AI books Some awesome AI related books and pdfs for downloading and learning. Preface This repo only used for learning, do not use in business

luckyzhou 1k Jan 01, 2023
Repository for "Space-Time Correspondence as a Contrastive Random Walk" (NeurIPS 2020)

Space-Time Correspondence as a Contrastive Random Walk This is the repository for Space-Time Correspondence as a Contrastive Random Walk, published at

A. Jabri 239 Dec 27, 2022