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
Code for the paper "Attention Approximates Sparse Distributed Memory"

Attention Approximates Sparse Distributed Memory - Codebase This is all of the code used to run analyses in the paper "Attention Approximates Sparse D

Trenton Bricken 14 Dec 05, 2022
Code, Data and Demo for Paper: Controllable Generation from Pre-trained Language Models via Inverse Prompting

InversePrompting Paper: Controllable Generation from Pre-trained Language Models via Inverse Prompting Code: The code is provided in the "chinese_ip"

THUDM 101 Dec 16, 2022
Code for our WACV 2022 paper "Hyper-Convolution Networks for Biomedical Image Segmentation"

Hyper-Convolution Networks for Biomedical Image Segmentation Code for our WACV 2022 paper "Hyper-Convolution Networks for Biomedical Image Segmentatio

Tianyu Ma 17 Nov 02, 2022
https://arxiv.org/abs/2102.11005

LogME LogME: Practical Assessment of Pre-trained Models for Transfer Learning How to use Just feed the features f and labels y to the function, and yo

THUML: Machine Learning Group @ THSS 149 Dec 19, 2022
Simulation of the solar system using various nummerical methods

solar-system Simulation of the solar system using various nummerical methods Download the repo Make shure matplotlib, scipy etc. are installed execute

Caspar 7 Jul 15, 2022
some academic posters as references. May we have in-person poster session soon!

some academic posters as references. May we have in-person poster session soon!

Bolei Zhou 472 Jan 06, 2023
PyTorch Implementation for "ForkGAN with SIngle Rainy NIght Images: Leveraging the RumiGAN to See into the Rainy Night"

ForkGAN with Single Rainy Night Images: Leveraging the RumiGAN to See into the Rainy Night By Seri Lee, Department of Engineering, Seoul National Univ

Seri Lee 52 Oct 12, 2022
OpenDelta - An Open-Source Framework for Paramter Efficient Tuning.

OpenDelta is a toolkit for parameter efficient methods (we dub it as delta tuning), by which users could flexibly assign (or add) a small amount parameters to update while keeping the most paramters

THUNLP 386 Dec 26, 2022
🎁 3,000,000+ Unsplash images made available for research and machine learning

The Unsplash Dataset The Unsplash Dataset is made up of over 250,000+ contributing global photographers and data sourced from hundreds of millions of

Unsplash 2k Jan 03, 2023
SwinIR: Image Restoration Using Swin Transformer

SwinIR: Image Restoration Using Swin Transformer This repository is the official PyTorch implementation of SwinIR: Image Restoration Using Shifted Win

Jingyun Liang 2.4k Jan 05, 2023
Code for the paper “The Peril of Popular Deep Learning Uncertainty Estimation Methods”

Uncertainty Estimation Methods Code for the paper “The Peril of Popular Deep Learning Uncertainty Estimation Methods” Reference If you use this code,

EPFL Machine Learning and Optimization Laboratory 4 Apr 05, 2022
Definition of a business problem according to Wilson Lower Bound Score and Time Based Average Rating

Wilson Lower Bound Score, Time Based Rating Average In this study I tried to calculate the product rating and sorting reviews more accurately. I have

3 Sep 30, 2021
Multi-Person Extreme Motion Prediction

Multi-Person Extreme Motion Prediction Implementation for paper Wen Guo, Xiaoyu Bie, Xavier Alameda-Pineda, Francesc Moreno-Noguer, Multi-Person Extre

GUO-W 38 Nov 15, 2022
DP-CL(Continual Learning with Differential Privacy)

DP-CL(Continual Learning with Differential Privacy) This is the official implementation of the Continual Learning with Differential Privacy. If you us

Phung Lai 3 Nov 04, 2022
Source code of CIKM2021 Long Paper "PSSL: Self-supervised Learning for Personalized Search with Contrastive Sampling".

PSSL Source code of CIKM2021 Long Paper "PSSL: Self-supervised Learning for Personalized Search with Contrastive Sampling". It consists of the pre-tra

2 Dec 21, 2021
Code for A Volumetric Transformer for Accurate 3D Tumor Segmentation

VT-UNet This repo contains the supported pytorch code and configuration files to reproduce 3D medical image segmentaion results of VT-UNet. Environmen

Himashi Amanda Peiris 114 Dec 20, 2022
Source code of SIGIR2021 Paper 'One Chatbot Per Person: Creating Personalized Chatbots based on Implicit Profiles'

DHAP Source code of SIGIR2021 Long Paper: One Chatbot Per Person: Creating Personalized Chatbots based on Implicit User Profiles . Preinstallation Fir

ZYMa 32 Dec 06, 2022
3rd Place Solution for ICCV 2021 Workshop SSLAD Track 3A - Continual Learning Classification Challenge

Online Continual Learning via Multiple Deep Metric Learning and Uncertainty-guided Episodic Memory Replay 3rd Place Solution for ICCV 2021 Workshop SS

Rifki Kurniawan 6 Nov 10, 2022
Hierarchical Attentive Recurrent Tracking

Hierarchical Attentive Recurrent Tracking This is an official Tensorflow implementation of single object tracking in videos by using hierarchical atte

Adam Kosiorek 147 Aug 07, 2021
A curated list of Machine Learning and Deep Learning tutorials in Jupyter Notebook format ready to run in Google Colaboratory

Awesome Machine Learning Jupyter Notebooks for Google Colaboratory A curated list of Machine Learning and Deep Learning tutorials in Jupyter Notebook

Carlos Toxtli 245 Jan 01, 2023