Skip to content

Instantly share code, notes, and snippets.

@mschmitt
Forked from webghostx/day-night-detection.py
Last active October 7, 2021 09:44
Show Gist options
  • Save mschmitt/58159734183423e565b70cdf90475557 to your computer and use it in GitHub Desktop.
Save mschmitt/58159734183423e565b70cdf90475557 to your computer and use it in GitHub Desktop.
day/night detection for cron jobs
# Run every minute and do things IF NOT night.
* * * * * (is_night || do_things) >/dev/null 2>&1
# Run every hour and do things IF night.
0 * * * * (is_night && do_things) >/dev/null 2>&1
#!/usr/bin/python3
import ephem
import time
import sys
home = ephem.Observer()
home.lat = '50.5'
home.lon = '8.7'
next_sunrise = home.next_rising(ephem.Sun()).datetime()
next_sunset = home.next_setting(ephem.Sun()).datetime()
if next_sunset < next_sunrise:
print("NOT NIGHT rc=1")
sys.exit(1)
else:
print("NIGHT rc=0")
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment