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
Leaf: Multiple-Choice Question Generation

Leaf: Multiple-Choice Question Generation Easy to use and understand multiple-choice question generation algorithm using T5 Transformers. The applicat

Kristiyan Vachev 62 Dec 20, 2022
MOpt-AFL provided by the paper "MOPT: Optimized Mutation Scheduling for Fuzzers"

MOpt-AFL 1. Description MOpt-AFL is a AFL-based fuzzer that utilizes a customized Particle Swarm Optimization (PSO) algorithm to find the optimal sele

172 Dec 18, 2022
Locally Enhanced Self-Attention: Rethinking Self-Attention as Local and Context Terms

LESA Introduction This repository contains the official implementation of Locally Enhanced Self-Attention: Rethinking Self-Attention as Local and Cont

Chenglin Yang 20 Dec 31, 2021
Unofficial PyTorch implementation of Neural Additive Models (NAM) by Agarwal, et al.

nam-pytorch Unofficial PyTorch implementation of Neural Additive Models (NAM) by Agarwal, et al. [abs, pdf] Installation You can access nam-pytorch vi

Rishabh Anand 11 Mar 14, 2022
Codes for "Solving Long-tailed Recognition with Deep Realistic Taxonomic Classifier"

Deep-RTC [project page] This repository contains the source code accompanying our ECCV 2020 paper. Solving Long-tailed Recognition with Deep Realistic

Gina Wu 16 May 26, 2022
Simple PyTorch hierarchical models.

A python package adding basic hierarchal networks in pytorch for classification tasks. It implements a simple hierarchal network structure based on feed-backward outputs.

Rajiv Sarvepalli 5 Mar 06, 2022
CRISCE: Automatically Generating Critical Driving Scenarios From Car Accident Sketches

CRISCE: Automatically Generating Critical Driving Scenarios From Car Accident Sketches This document describes how to install and use CRISCE (CRItical

Chair of Software Engineering II, Uni Passau 2 Feb 09, 2022
Multi-Modal Fingerprint Presentation Attack Detection: Evaluation On A New Dataset

PADISI USC Dataset This repository analyzes the PADISI-Finger dataset introduced in Multi-Modal Fingerprint Presentation Attack Detection: Evaluation

USC ISI VISTA Computer Vision 6 Feb 06, 2022
Enabling Lightweight Fine-tuning for Pre-trained Language Model Compression based on Matrix Product Operators

Enabling Lightweight Fine-tuning for Pre-trained Language Model Compression based on Matrix Product Operators This is our Pytorch implementation for t

RUCAIBox 12 Jul 22, 2022
An All-MLP solution for Vision, from Google AI

MLP Mixer - Pytorch An All-MLP solution for Vision, from Google AI, in Pytorch. No convolutions nor attention needed! Yannic Kilcher video Install $ p

Phil Wang 784 Jan 06, 2023
AI grand challenge 2020 Repo (Speech Recognition Track)

KorBERT를 활용한 한국어 텍스트 기반 위협 상황인지(2020 인공지능 그랜드 챌린지) 본 프로젝트는 ETRI에서 제공된 한국어 korBERT 모델을 활용하여 폭력 기반 한국어 텍스트를 분류하는 다양한 분류 모델들을 제공합니다. 본 개발자들이 참여한 2020 인공지

Young-Seok Choi 23 Jan 25, 2022
A simple python module to generate anchor (aka default/prior) boxes for object detection tasks.

PyBx WIP A simple python module to generate anchor (aka default/prior) boxes for object detection tasks. Calculated anchor boxes are returned as ndarr

thatgeeman 4 Dec 15, 2022
(NeurIPS 2021) Pytorch implementation of paper "Re-ranking for image retrieval and transductive few-shot classification"

SSR (NeurIPS 2021) Pytorch implementation of paper "Re-ranking for image retrieval and transductivefew-shot classification" [Paper] [Project webpage]

xshen 29 Dec 06, 2022
[CVPR 2021 Oral] ForgeryNet: A Versatile Benchmark for Comprehensive Forgery Analysis

ForgeryNet: A Versatile Benchmark for Comprehensive Forgery Analysis ForgeryNet: A Versatile Benchmark for Comprehensive Forgery Analysis [arxiv|pdf|v

Yinan He 78 Dec 22, 2022
Brain tumor detection using Convolution-Neural Network (CNN)

Detect and Classify Brain Tumor using CNN. A system performing detection and classification by using Deep Learning Algorithms using Convolution-Neural Network (CNN).

assia 1 Feb 07, 2022
Code for "Long-tailed Distribution Adaptation"

Long-tailed Distribution Adaptation (Accepted in ACM MM2021) This project is built upon BBN. Installation pip install -r requirements.txt Usage Traini

Zhiliang Peng 10 May 18, 2022
For IBM Quantum Challenge 2021 (May 20 - 26)

IBM Quantum Challenge 2021 Introduction Commemorating the 40-year anniversary of the Physics of Computation conference, and 5-year anniversary of IBM

Qiskit Community 140 Jan 01, 2023
Official code repository for the work: "The Implicit Values of A Good Hand Shake: Handheld Multi-Frame Neural Depth Refinement"

Handheld Multi-Frame Neural Depth Refinement This is the official code repository for the work: The Implicit Values of A Good Hand Shake: Handheld Mul

55 Dec 14, 2022
September-Assistant - Open-source Windows Voice Assistant

September - Windows Assistant September is an open-source Windows personal assis

The Nithin Balaji 9 Nov 22, 2022
Official code for the publication "HyFactor: Hydrogen-count labelled graph-based defactorization Autoencoder".

HyFactor Graph-based architectures are becoming increasingly popular as a tool for structure generation. Here, we introduce a novel open-source archit

Laboratoire-de-Chemoinformatique 11 Oct 10, 2022