pax_global_header00006660000000000000000000000064135307532470014523gustar00rootroot0000000000000052 comment=59f4b10f42e184e90d2a88a0459056279c70aca4 suntime-1.2.5/000077500000000000000000000000001353075324700132145ustar00rootroot00000000000000suntime-1.2.5/.gitignore000066400000000000000000000001151353075324700152010ustar00rootroot00000000000000.idea/ .eggs/ build/ dist/ example.py suntime.egg-info/ suntime/__pycache__/ suntime-1.2.5/LICENSE000066400000000000000000000167431353075324700142340ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. suntime-1.2.5/README.md000066400000000000000000000045061353075324700145000ustar00rootroot00000000000000# SunTime Simple sunset and sunrise time calculation python library. ## Installation Using pip: pip3 install suntime Or download and type: python3 setup.py install ## Usage You can use the library to get UTC and local time sunrise and sunset times typing: ```python3 import datetime from suntime import Sun, SunTimeException latitude = 51.21 longitude = 21.01 sun = Sun(latitude, longitude) # Get today's sunrise and sunset in UTC today_sr = sun.get_sunrise_time() today_ss = sun.get_sunset_time() print('Today at Warsaw the sun raised at {} and get down at {} UTC'. format(today_sr.strftime('%H:%M'), today_ss.strftime('%H:%M'))) # On a special date in your machine's local time zone abd = datetime.date(2014, 10, 3) abd_sr = sun.get_local_sunrise_time(abd) abd_ss = sun.get_local_sunset_time(abd) print('On {} the sun at Warsaw raised at {} and get down at {}.'. format(abd, abd_sr.strftime('%H:%M'), abd_ss.strftime('%H:%M'))) # Error handling (no sunset or sunrise on given location) latitude = 87.55 longitude = 0.1 sun = Sun(latitude, longitude) try: abd_sr = sun.get_local_sunrise_time(abd) abd_ss = sun.get_local_sunset_time(abd) print('On {} at somewhere in the north the sun raised at {} and get down at {}.'. format(abd, abd_sr.strftime('%H:%M'), abd_ss.strftime('%H:%M'))) except SunTimeException as e: print("Error: {0}.".format(e)) ``` ## License Copyright © 2019 SatAgro Sp. z o.o. and contributors: * Krzysztof Stopa ([kstopa](https://github.com/kstopa)) * Andrey Kobyshev ([yokotoka](https://github.com/yokotoka)) * Matthias ([palto42](https://github.com/plato42)) * Hadrien Bertrand ([hbertrand](https://github.com/hbertrand)) This file is part of SunTime library for python (SunTime). SunTime is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. SunTime is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with CAMS tools. If not, see http://www.gnu.org/licenses/. suntime-1.2.5/setup.py000066400000000000000000000012011353075324700147200ustar00rootroot00000000000000#!/usr/bin/env python from setuptools import setup # read the contents of your README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md')) as f: long_description = f.read() setup(name='suntime', version='1.2.5', description='Simple sunset and sunrise time calculation python library', long_description=long_description, author='Krzysztof Stopa', url='https://github.com/SatAgro/suntime', copyright='Copyright 2019 SatAgro', license='LGPLv3', packages=['suntime'], install_requires=['python-dateutil'] ) suntime-1.2.5/suntime/000077500000000000000000000000001353075324700147005ustar00rootroot00000000000000suntime-1.2.5/suntime/__init__.py000066400000000000000000000000531353075324700170070ustar00rootroot00000000000000from .suntime import Sun, SunTimeException suntime-1.2.5/suntime/suntime.py000066400000000000000000000157271353075324700167520ustar00rootroot00000000000000import calendar import math import datetime from dateutil import tz class SunTimeException(Exception): def __init__(self, message): super(SunTimeException, self).__init__(message) class Sun: """ Approximated calculation of sunrise and sunset datetimes. Adapted from: https://stackoverflow.com/questions/19615350/calculate-sunrise-and-sunset-times-for-a-given-gps-coordinate-within-postgresql """ def __init__(self, lat, lon): self._lat = lat self._lon = lon def get_sunrise_time(self, date=None): """ Calculate the sunrise time for given date. :param lat: Latitude :param lon: Longitude :param date: Reference date. Today if not provided. :return: UTC sunrise datetime :raises: SunTimeException when there is no sunrise and sunset on given location and date """ date = datetime.date.today() if date is None else date sr = self._calc_sun_time(date, True) if sr is None: raise SunTimeException('The sun never rises on this location (on the specified date)') else: return sr def get_local_sunrise_time(self, date=None, local_time_zone=tz.tzlocal()): """ Get sunrise time for local or custom time zone. :param date: Reference date. Today if not provided. :param local_time_zone: Local or custom time zone. :return: Local time zone sunrise datetime """ date = datetime.date.today() if date is None else date sr = self._calc_sun_time(date, True) if sr is None: raise SunTimeException('The sun never rises on this location (on the specified date)') else: return sr.astimezone(local_time_zone) def get_sunset_time(self, date=None): """ Calculate the sunset time for given date. :param lat: Latitude :param lon: Longitude :param date: Reference date. Today if not provided. :return: UTC sunset datetime :raises: SunTimeException when there is no sunrise and sunset on given location and date. """ date = datetime.date.today() if date is None else date ss = self._calc_sun_time(date, False) if ss is None: raise SunTimeException('The sun never sets on this location (on the specified date)') else: return ss def get_local_sunset_time(self, date=None, local_time_zone=tz.tzlocal()): """ Get sunset time for local or custom time zone. :param date: Reference date :param local_time_zone: Local or custom time zone. :return: Local time zone sunset datetime """ date = datetime.date.today() if date is None else date ss = self._calc_sun_time(date, False) if ss is None: raise SunTimeException('The sun never sets on this location (on the specified date)') else: return ss.astimezone(local_time_zone) def _calc_sun_time(self, date, isRiseTime=True, zenith=90.8): """ Calculate sunrise or sunset date. :param date: Reference date :param isRiseTime: True if you want to calculate sunrise time. :param zenith: Sun reference zenith :return: UTC sunset or sunrise datetime :raises: SunTimeException when there is no sunrise and sunset on given location and date """ # isRiseTime == False, returns sunsetTime day = date.day month = date.month year = date.year TO_RAD = math.pi/180.0 # 1. first calculate the day of the year N1 = math.floor(275 * month / 9) N2 = math.floor((month + 9) / 12) N3 = (1 + math.floor((year - 4 * math.floor(year / 4) + 2) / 3)) N = N1 - (N2 * N3) + day - 30 # 2. convert the longitude to hour value and calculate an approximate time lngHour = self._lon / 15 if isRiseTime: t = N + ((6 - lngHour) / 24) else: #sunset t = N + ((18 - lngHour) / 24) # 3. calculate the Sun's mean anomaly M = (0.9856 * t) - 3.289 # 4. calculate the Sun's true longitude L = M + (1.916 * math.sin(TO_RAD*M)) + (0.020 * math.sin(TO_RAD * 2 * M)) + 282.634 L = self._force_range(L, 360 ) #NOTE: L adjusted into the range [0,360) # 5a. calculate the Sun's right ascension RA = (1/TO_RAD) * math.atan(0.91764 * math.tan(TO_RAD*L)) RA = self._force_range(RA, 360 ) #NOTE: RA adjusted into the range [0,360) # 5b. right ascension value needs to be in the same quadrant as L Lquadrant = (math.floor( L/90)) * 90 RAquadrant = (math.floor(RA/90)) * 90 RA = RA + (Lquadrant - RAquadrant) # 5c. right ascension value needs to be converted into hours RA = RA / 15 # 6. calculate the Sun's declination sinDec = 0.39782 * math.sin(TO_RAD*L) cosDec = math.cos(math.asin(sinDec)) # 7a. calculate the Sun's local hour angle cosH = (math.cos(TO_RAD*zenith) - (sinDec * math.sin(TO_RAD*self._lat))) / (cosDec * math.cos(TO_RAD*self._lat)) if cosH > 1: return None # The sun never rises on this location (on the specified date) if cosH < -1: return None # The sun never sets on this location (on the specified date) # 7b. finish calculating H and convert into hours if isRiseTime: H = 360 - (1/TO_RAD) * math.acos(cosH) else: #setting H = (1/TO_RAD) * math.acos(cosH) H = H / 15 #8. calculate local mean time of rising/setting T = H + RA - (0.06571 * t) - 6.622 #9. adjust back to UTC UT = T - lngHour UT = self._force_range(UT, 24) # UTC time in decimal format (e.g. 23.23) #10. Return hr = self._force_range(int(UT), 24) min = round((UT - int(UT))*60, 0) if min == 60: hr += 1 min = 0 #10. check corner case https://github.com/SatAgro/suntime/issues/1 if hr == 24: hr = 0 day += 1 if day > calendar.monthrange(year, month)[1]: day = 1 month += 1 if month > 12: month = 1 year += 1 return datetime.datetime(year, month, day, hr, int(min), tzinfo=tz.tzutc()) @staticmethod def _force_range(v, max): # force v to be >= 0 and < max if v < 0: return v + max elif v >= max: return v - max return v if __name__ == '__main__': sun = Sun(85.0, 21.00) try: print(sun.get_local_sunrise_time()) print(sun.get_local_sunset_time()) # On a special date in UTC abd = datetime.date(2014, 1, 3) abd_sr = sun.get_local_sunrise_time(abd) abd_ss = sun.get_local_sunset_time(abd) print(abd_sr) print(abd_ss) except SunTimeException as e: print("Error: {0}".format(e))