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:john@d10cave:~/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
ShuttleNet: Position-aware Fusion of Rally Progress and Player Styles for Stroke Forecasting in Badminton (AAAI 2022)

ShuttleNet: Position-aware Rally Progress and Player Styles Fusion for Stroke Forecasting in Badminton (AAAI 2022) Official code of the paper ShuttleN

Wei-Yao Wang 11 Nov 30, 2022
(CVPR 2021) PAConv: Position Adaptive Convolution with Dynamic Kernel Assembling on Point Clouds

PAConv: Position Adaptive Convolution with Dynamic Kernel Assembling on Point Clouds by Mutian Xu*, Runyu Ding*, Hengshuang Zhao, and Xiaojuan Qi. Int

CVMI Lab 228 Dec 25, 2022
3D position tracking for soccer players with multi-camera videos

This repo contains a full pipeline to support 3D position tracking of soccer players, with multi-view calibrated moving/fixed video sequences as inputs.

Yuchang Jiang 72 Dec 27, 2022
Position detection system of mobile robot in the warehouse enviroment

Autonomous-Forklift-System About | GUI | Tests | Starting | License | Author | ?? About An application that run the autonomous forklift paletization a

Kamil Goś 1 Nov 24, 2021
Python-experiments - A Repository which contains python scripts to automate things and make your life easier with python

Python Experiments A Repository which contains python scripts to automate things

Vivek Kumar Singh 11 Sep 25, 2022
Scalable, Portable and Distributed Gradient Boosting (GBDT, GBRT or GBM) Library, for Python, R, Java, Scala, C++ and more. Runs on single machine, Hadoop, Spark, Dask, Flink and DataFlow

eXtreme Gradient Boosting Community | Documentation | Resources | Contributors | Release Notes XGBoost is an optimized distributed gradient boosting l

Distributed (Deep) Machine Learning Community 23.6k Dec 31, 2022
Python Library for learning (Structure and Parameter) and inference (Statistical and Causal) in Bayesian Networks.

pgmpy pgmpy is a python library for working with Probabilistic Graphical Models. Documentation and list of algorithms supported is at our official sit

pgmpy 2.2k Jan 3, 2023
High performance, easy-to-use, and scalable machine learning (ML) package, including linear model (LR), factorization machines (FM), and field-aware factorization machines (FFM) for Python and CLI interface.

What is xLearn? xLearn is a high performance, easy-to-use, and scalable machine learning package that contains linear model (LR), factorization machin

Chao Ma 3k Jan 3, 2023
This repository is related to an Arabic tutorial, within the tutorial we discuss the common data structure and algorithms and their worst and best case for each, then implement the code using Python.

Data Structure and Algorithms with Python This repository is related to the Arabic tutorial here, within the tutorial we discuss the common data struc

Mohamed Ayman 33 Dec 2, 2022
Scalable, Portable and Distributed Gradient Boosting (GBDT, GBRT or GBM) Library, for Python, R, Java, Scala, C++ and more. Runs on single machine, Hadoop, Spark, Dask, Flink and DataFlow

eXtreme Gradient Boosting Community | Documentation | Resources | Contributors | Release Notes XGBoost is an optimized distributed gradient boosting l

Distributed (Deep) Machine Learning Community 20.6k Feb 13, 2021
High performance, easy-to-use, and scalable machine learning (ML) package, including linear model (LR), factorization machines (FM), and field-aware factorization machines (FFM) for Python and CLI interface.

What is xLearn? xLearn is a high performance, easy-to-use, and scalable machine learning package that contains linear model (LR), factorization machin

Chao Ma 2.8k Feb 12, 2021
All the essential resources and template code needed to understand and practice data structures and algorithms in python with few small projects to demonstrate their practical application.

Data Structures and Algorithms Python INDEX 1. Resources - Books Data Structures - Reema Thareja competitiveCoding Big-O Cheat Sheet DAA Syllabus Inte

Shushrut Kumar 129 Dec 15, 2022
DIT is a DTLS MitM proxy implemented in Python 3. It can intercept, manipulate and suppress datagrams between two DTLS endpoints and supports psk-based and certificate-based authentication schemes (RSA + ECC).

DIT - DTLS Interception Tool DIT is a MitM proxy tool to intercept DTLS traffic. It can intercept, manipulate and/or suppress DTLS datagrams between t

null 52 Nov 30, 2022
MM1 and MMC Queue Simulation using python - Results and parameters in excel and csv files

implementation of MM1 and MMC Queue on randomly generated data and evaluate simulation results then compare with analytical results and draw a plot curve for them, simulate some integrals and compare results and run monte carlo algorithm with them

Mohamadreza Rezaei 1 Jan 19, 2022