Skip to content

Instantly share code, notes, and snippets.

@kenners
Last active August 22, 2021 21:39
Show Gist options
  • Save kenners/7297cab1f205da998247 to your computer and use it in GitHub Desktop.
Save kenners/7297cab1f205da998247 to your computer and use it in GitHub Desktop.
Calculate sunrise and sunset times for Rothera Research Station
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Calculate local sunrise and sunset times for Rothera.
"""
import ephem
from datetime import date, datetime
import argparse
def sunrise(location, day, horizon, dawn='True'):
"""
Calculate sunrise/set time and return it as a Julian Date.
Args:
location (object): an ephem.Observer object
day (int/float): the Julian Day or Date
horizon (int/float): the angle of the desired horizon e.g. astronomical dawn is -18
dawn (bool): Dawn (True) or dusk (False)
Returns:
suntime (float): the Julian Date of the sunrise/sunset
Raises:
CircumpolarError: If sun does not rise or set during the Julian Day.
"""
location.date = day
location.horizon = horizon
sun = ephem.Sun()
sun.compute(location)
if dawn is True:
try:
suntime = ephem.localtime(location.next_rising(sun))
except ephem.CircumpolarError:
suntime = ephem.Date(day).datetime()
else:
try:
suntime = ephem.localtime(location.next_setting(sun))
except ephem.CircumpolarError:
suntime = ephem.Date(day).datetime()
return suntime
def is_date(input_date):
"""Checks whether the input date is a valid date."""
if input_date in ['tod', 'today']:
day = ephem.Date(date.today())
elif input_date in ['tom', 'tomorrow']:
day = ephem.Date(date.today()) + 1
elif input_date in ['yest', 'yesterday']:
day = ephem.Date(date.today() - 1)
else:
try:
day = ephem.Date(datetime.strptime(input_date, '%Y-%m-%d'))
except ValueError:
raise argparse.ArgumentTypeError('Invalid date – must be in format YYYY-MM-DD')
return day
def main():
parser = argparse.ArgumentParser(description="Calculates current sunset and sunrise for Rothera.")
parser.add_argument("day", type=is_date, nargs='?', default=ephem.Date(date.today()), help="Date in YYYY-MM-DD. Defaults to today.")
args = parser.parse_args()
rothera = ephem.Observer()
rothera.lat = '-67.57'
rothera.lon = '-68.13'
rothera.pressure = 0
# -6º is civil twilight; –0:34º with 0 pressure is the NOAA spec for
# sunrise/set to take into account atmospheric refraction
horizons = ['-6','-0:34']
day = args.day
srises = [sunrise(rothera, day, horizon, True) for horizon in horizons]
ssets = [sunrise(rothera, day, horizon, False) for horizon in reversed(horizons)]
now = datetime.now()
if ssets[1] < now:
daylight_left = 'None'
else:
if now > srises[0]:
daylight_left = str(ssets[1] - now)
else:
daylight_left = str(ssets[1] - srises[0])
sunrises = [srise.strftime('%H:%M') for srise in srises]
sunsets = [sset.strftime('%H:%M') for sset in ssets]
output = sunrises + sunsets
print("Dawn: {0} Sunrise: {1} Sunset: {2} Dusk: {3}".format(*output))
print("Daylight left: {0}".format(daylight_left))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment