timelapse/getdayinfo.py

72 lines
2.9 KiB
Python
Executable File

#!/usr/bin/python
import os, urllib2 as url, json
import datetime as dt
from optparse import OptionParser
# Greenwich Observatory
lat="51.4826"
lng="0.000"
optparse = OptionParser(usage="Usage: %prog [options]")
optparse.add_option('-d','--date',dest='date',help='Set date to qurey YYYY-MM-DD [default=today]',default='today')
optparse.add_option('-t','--timetype',dest='ttype',help='Set sunrise/sunset type (standard,civil,nautical,astronomical) [default=standard] see https://www.timeanddate.com/astronomy/different-types-twilight.html',default='standard')
optparse.add_option('-i','--interval',dest='interval',help='Minute Interval [default=1, max=60]',default='1')
optparse.add_option('-x','--lat',dest='lat',help='Latitude defaults to ' + lat,default=lat)
optparse.add_option('-y','--lng',dest='lng',help='Longitude defaults to ' + lng,default=lng)
(options, args) = optparse.parse_args()
def min_round(x,base):
minute = dt.datetime.strptime(str(int(base * int(float(x)/base))),'%M')
return minute.strftime("%M")
def riseset_info(lat,lng,date,ttype):
ret = {}
apiUrl="https://api.sunrise-sunset.org/json?lat=" + str(lat) + "&lng=" + str(lng) + "&date=" + str(date)
response = url.urlopen(apiUrl).read()
result = json.loads(response)
if ttype == 'standard':
sunrise = result['results']['sunrise']
sunset = result['results']['sunset']
elif ttype == 'civil':
sunrise = result['results']['civil_twilight_begin']
sunset = result['results']['civil_twilight_end']
elif ttype == 'nautical':
sunrise = result['results']['nautical_twilight_begin']
sunset = result['results']['nautical_twilight_end']
elif ttype == 'astronomical':
sunrise = result['results']['astronomical_twilight_begin']
sunset = result['results']['astronomical_twilight_end']
else:
print
print "ERROR: Invalid Time Type"
print
optparse.print_help()
print
os._exit(1)
srtime = dt.datetime.strptime(sunrise,"%I:%M:%S %p")
sstime = dt.datetime.strptime(sunset,"%I:%M:%S %p")
sunrise_H = srtime.strftime("%H")
sunrise_M = srtime.strftime("%M")
sunrise_MR = min_round(x=sunrise_M,base=int(options.interval))
srtime = dt.datetime.strptime(sunrise_H + ':' + str(sunrise_MR),"%H:%M")
ret['sunrise'] = srtime.strftime("%H%M")
sunset_H = sstime.strftime("%H")
sunset_M = sstime.strftime("%M")
sunset_MR = min_round(x=sunset_M,base=int(options.interval))
if sunset_M != sunset_MR:
sunset_MR = sunset_MR + int(options.interval)
if sunset_MR == 60:
sunset_H = sunset_H + 1
sunset_MR = 0
sstime = dt.datetime.strptime(sunset_H + ':' + str(sunset_MR),"%H:%M")
ret['sunset'] = sstime.strftime("%H%M")
return ret
print riseset_info(lat=options.lat,lng=options.lng,date=options.date,ttype=options.ttype)