Last active
November 6, 2017 13:09
-
-
Save tricoder42/4124405 to your computer and use it in GitHub Desktop.
Show times for dusk, dawn, sunset and sunrise.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
Usage: twilight.py [--city=<city> | --coordinates=<coordinates>] | |
[--date=<date> | --tomorrow] [--week] | |
[-h | --help | --version] | |
Options: | |
-h --help Show this help. | |
--version Show version. | |
-d --date=<date> Set date, YYYY-MM-DD | |
-t --tomorrow Set date for tomorrow. | |
-w --week Show times for whole week (today + 7 days) | |
--city=<city> Set coordinates to following city (see ephem documentation) | |
-c --coordinates=<latitude>,<longitude> | |
Set coordinates in degrees | |
""" | |
import datetime | |
import docopt | |
import ephem | |
import math | |
__version__ = '0.1' | |
__author__ = 'Tomáš Ehrlich <tomas.ehrlich@gmail.com>' | |
arguments = docopt.docopt(__doc__, version=__version__) | |
coordinates_override = { | |
'Brno': '49.19729,16.60362' | |
} | |
radians = lambda d: d*math.pi/180 | |
local = lambda d: ephem.localtime(d) | |
TIME_FORMAT = '%H:%M:%S' | |
DATE_FORMAT = '%A %d. %B' | |
sun = ephem.Sun() | |
# Set location | |
coords = arguments.get('--coordinates', None) | |
city = arguments.get('--city') or 'Brno' | |
if city in coordinates_override: | |
coords = coordinates_override[city] | |
if coords: | |
obs = ephem.Observer() | |
obs.lat, obs.lon = map(radians, map(float, coords.split(','))) | |
else: | |
obs = ephem.city(city) | |
# Set date | |
date = arguments.get('--date', None) | |
if date: | |
date = datetime.datetime.strptime(date, '%Y-%m-%d').date() | |
else: | |
date = datetime.date.today() | |
if arguments['--tomorrow'] and not arguments['--week']: | |
date += datetime.timedelta(days=1) | |
day_range = arguments['--week'] and 7 or 1 | |
print 'Location: {}, {}'.format(obs.lat, obs.lon) | |
for interval in range(day_range): | |
obs.date = date + datetime.timedelta(days=interval) | |
obs.horizon = '0' | |
sunrise, sunset = map(local, (obs.next_rising(sun), obs.next_setting(sun))) | |
obs.horizon = '-6' | |
dawn, dusk = map(local, (obs.next_rising(sun), obs.next_setting(sun))) | |
print obs.date.datetime().strftime(DATE_FORMAT) | |
print 'Dawn:\t\t{}'.format(dawn.strftime(TIME_FORMAT)) | |
print 'Sunrise:\t{}'.format(sunrise.strftime(TIME_FORMAT)) | |
print 'Sunset: \t{}'.format(sunset.strftime(TIME_FORMAT)) | |
print 'Dusk:\t\t{}'.format(dusk.strftime(TIME_FORMAT)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this, it was exactly what I was looking for.