or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-suntime

Simple sunset and sunrise time calculation python library

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/suntime@1.3.x

To install, run

npx @tessl/cli install tessl/pypi-suntime@1.3.0

index.mddocs/

SunTime

Simple sunset and sunrise time calculation python library. Provides astronomical calculations for determining sunrise and sunset times for any geographic location and date, with support for various timezones and edge case handling for polar regions.

Package Information

  • Package Name: suntime
  • Language: Python
  • Installation: pip install suntime
  • License: LGPLv3
  • Version: 1.3.2

Core Imports

from suntime import Sun, SunTimeException

Basic Usage

import datetime
from dateutil import tz
from suntime import Sun, SunTimeException

# Create Sun instance with coordinates (Warsaw, Poland)
warsaw_lat = 51.21
warsaw_lon = 21.01
sun = Sun(warsaw_lat, warsaw_lon)

# Get today's sunrise and sunset in UTC
today_sr = sun.get_sunrise_time()
today_ss = sun.get_sunset_time()
print(f'Today at Warsaw the sun raised at {today_sr.strftime("%H:%M")} and set at {today_ss.strftime("%H:%M")} UTC')

# Get sunrise and sunset for specific date with timezone
specific_date = datetime.date(2024, 10, 3)
local_tz = tz.gettz('Europe/Warsaw')
abd_sr = sun.get_sunrise_time(specific_date, local_tz)
abd_ss = sun.get_sunset_time(specific_date, local_tz)
print(f'On {specific_date} the sun raised at {abd_sr.strftime("%H:%M")} and set at {abd_ss.strftime("%H:%M")}')

# Error handling for polar regions
try:
    north_sun = Sun(87.55, 0.1)  # High latitude
    polar_sunrise = north_sun.get_sunrise_time(specific_date)
except SunTimeException as e:
    print(f"Error: {e}")

Capabilities

Sunrise Calculation

Calculate sunrise time for a given location and date with timezone support.

def get_sunrise_time(self, at_date=datetime.now(), time_zone=timezone.utc):
    """
    Calculate sunrise time for specified date and timezone.
    
    Parameters:
    - at_date: datetime, reference date (defaults to current date)
    - time_zone: timezone object with tzinfo(), defaults to UTC
    
    Returns:
    datetime: Sunrise datetime object
    
    Raises:
    SunTimeException: When there is no sunrise on given location and date
    """

Sunset Calculation

Calculate sunset time for a given location and date with timezone support.

def get_sunset_time(self, at_date=datetime.now(), time_zone=timezone.utc):
    """
    Calculate sunset time for specified date and timezone.
    
    Parameters:
    - at_date: datetime, reference date (defaults to current date)
    - time_zone: timezone object with tzinfo(), defaults to UTC
    
    Returns:
    datetime: Sunset datetime object
    
    Raises:
    SunTimeException: When there is no sunset on given location and date
    """

Low-Level Sun Time Calculation

Advanced method for calculating sunrise or sunset with custom zenith angle.

def get_sun_timedelta(self, at_date, time_zone, is_rise_time=True, zenith=90.8):
    """
    Calculate sunrise or sunset timedelta with custom zenith angle.
    
    Parameters:
    - at_date: datetime, reference date
    - time_zone: timezone object with tzinfo()
    - is_rise_time: bool, True for sunrise, False for sunset (default: True)
    - zenith: float, sun reference zenith angle in degrees (default: 90.8)
    
    Returns:
    timedelta: Time offset for sunrise/sunset, or None if sun doesn't rise/set
    """

Deprecated Methods

Legacy methods maintained for backward compatibility.

def get_local_sunrise_time(self, at_date=datetime.now(), time_zone=None):
    """
    DEPRECATED: Use get_sunrise_time() with proper timezone instead.
    
    Parameters:
    - at_date: datetime, reference date (defaults to current date)
    - time_zone: timezone object, defaults to None
    
    Returns:
    datetime: Sunrise datetime object
    """

def get_local_sunset_time(self, at_date=datetime.now(), time_zone=None):
    """
    DEPRECATED: Use get_sunset_time() with proper timezone instead.
    
    Parameters:
    - at_date: datetime, reference date (defaults to current date)
    - time_zone: timezone object, defaults to None
    
    Returns:
    datetime: Sunset datetime object
    """

Types

Sun Class

Main class for sunrise and sunset calculations.

class Sun:
    """
    Approximated calculation of sunrise and sunset datetimes.
    
    Uses astronomical algorithms to calculate sun times for any geographic location.
    Handles edge cases for polar regions where sun may not rise or set.
    """
    
    def __init__(self, lat, lon):
        """
        Initialize Sun instance with geographic coordinates.
        
        Parameters:
        - lat: float, latitude in decimal degrees (-90 to +90)
        - lon: float, longitude in decimal degrees (-180 to +180)
        """
    
    # Computed attribute
    lngHour: float  # Longitude converted to hours (lon / 15)

Exception Classes

class SunTimeException(Exception):
    """
    Exception raised when sunrise/sunset cannot be calculated.
    
    Typically occurs in polar regions during certain seasons where
    the sun does not rise or set on specific dates.
    """
    
    def __init__(self, message):
        """
        Initialize exception with error message.
        
        Parameters:
        - message: str, descriptive error message
        """

Module Constants

__version__: str  # Package version string ('1.3.2')
__author__: str   # Author name ('Krzysztof Stopa')
__license__: str  # License type ('LGPLv3')

Usage Examples

Working with Different Timezones

import datetime
from dateutil import tz
from suntime import Sun

# Create sun instance for New York
ny_sun = Sun(40.7128, -74.0060)

# Get times in different timezones
utc_sunrise = ny_sun.get_sunrise_time()
local_sunrise = ny_sun.get_sunrise_time(time_zone=tz.gettz('America/New_York'))
london_sunrise = ny_sun.get_sunrise_time(time_zone=tz.gettz('Europe/London'))

print(f"NYC sunrise in UTC: {utc_sunrise}")
print(f"NYC sunrise in local time: {local_sunrise}")
print(f"NYC sunrise in London time: {london_sunrise}")

Historical and Future Dates

from suntime import Sun
import datetime

sun = Sun(48.8566, 2.3522)  # Paris coordinates

# Historical date
historical_date = datetime.date(1969, 7, 20)  # Moon landing
historical_sunrise = sun.get_sunrise_time(historical_date)

# Future date
future_date = datetime.date(2030, 1, 1)
future_sunset = sun.get_sunset_time(future_date)

print(f"Paris sunrise on Moon landing day: {historical_sunrise}")
print(f"Paris sunset on New Year 2030: {future_sunset}")

Error Handling for Extreme Latitudes

from suntime import Sun, SunTimeException
import datetime

# Test polar region during winter
arctic_sun = Sun(80.0, 0.0)  # High Arctic
winter_date = datetime.date(2024, 12, 21)  # Winter solstice

try:
    sunrise = arctic_sun.get_sunrise_time(winter_date)
    print(f"Arctic sunrise: {sunrise}")
except SunTimeException as e:
    print(f"No sunrise in Arctic winter: {e}")

try:
    sunset = arctic_sun.get_sunset_time(winter_date)
    print(f"Arctic sunset: {sunset}")
except SunTimeException as e:
    print(f"No sunset in Arctic winter: {e}")

Custom Zenith Calculations

from suntime import Sun
import datetime

sun = Sun(37.7749, -122.4194)  # San Francisco
date = datetime.date(2024, 6, 21)  # Summer solstice

# Standard zenith (90.8°) - accounts for atmospheric refraction
standard_delta = sun.get_sun_timedelta(date, None, is_rise_time=True)

# Geometric horizon (90°)
geometric_delta = sun.get_sun_timedelta(date, None, is_rise_time=True, zenith=90.0)

# Civil twilight (96°)
civil_delta = sun.get_sun_timedelta(date, None, is_rise_time=True, zenith=96.0)

print(f"Standard sunrise offset: {standard_delta}")
print(f"Geometric sunrise offset: {geometric_delta}")
print(f"Civil twilight offset: {civil_delta}")