def get_daylight_details(): """Get details of solar path/daylight hours at site for today (local)""" # Instantiating Astral object (for calculating position of sun and moon) a = Astral() a.solar_depression = 'civil' # Instantiating an Astral location (hard-coded here since dealing with one site only, but # easily scalable if site required login and site lat and long were tied to user profile) l = Location() l.latitude = 37.8195 l.longitude = -122.2523 l.timezone = 'US/Pacific' l.elevation = 125 sunrise = l.sunrise().strftime('%-I:%M%p') sunset = l.sunset().strftime('%-I:%M%p') day_length = str(l.sunset() - l.sunrise()) solar_noon = l.solar_noon().strftime('%-I:%M%p') solar_zenith = l.solar_elevation(l.solar_noon().replace(tzinfo=None)) solar_elevation = l.solar_elevation() daylight_data = { 'sunrise': sunrise, 'sunset': sunset, 'daylength': day_length, 'solar_noon': solar_noon, 'zenith': solar_zenith, 'elevation': solar_elevation } return jsonify(daylight_data)
def is_at_night(mo=None): try: a = Location() a.timezone = settings.TIME_ZONE tz = pytz.timezone(a.timezone) #Tue, 22 Jul 2008 08:17:41 +0200 #Sun, 26 Jan 2014 17:39:49 +01:00 a_sunset = a.sunset() a_sunrise = a.sunrise() n = datetime.datetime.now() n = tz.localize(n) logger.debug("NOW: %s; sunrise: %s; dif: %s" % (n, a_sunrise, n - a_sunrise)) logger.debug("NOW: %s; sunset: %s; dif: %s" % (n, a_sunset, n - a_sunset)) passed_sunrise = (n - a_sunrise) > datetime.timedelta(minutes=settings.MINUTES_AFTER_SUNRISE_FOR_DAY) logger.debug("Passed %s sunrise more than %s minutes" % (passed_sunrise, settings.MINUTES_AFTER_SUNRISE_FOR_DAY)) passed_sunset = (n - a_sunset) > datetime.timedelta(minutes=settings.MINUTES_AFTER_SUNSET_FOR_DAY) logger.debug("Passed %s sunset more than %s minutes" % (passed_sunset, settings.MINUTES_AFTER_SUNSET_FOR_DAY)) if not passed_sunrise or passed_sunset: logger.debug("Is at night") return 1 if passed_sunrise and not passed_sunset: logger.debug("Is not at night") return 0 except Exception as ex: logger.error(ex)
def is_day(self): l = Location() l.latitude = self.latitude l.longitude = self.longitude current_time = datetime.now(l.tzinfo) if (l.sunset() > current_time) and (l.sunrise() < current_time): return True else: return False
def doAction(self,r,sr,words,sensorList): if self.tz == None: os.system("espeak -s 120 'loading solar data'") self.tz = tzwhere.tzwhere() fix = sensorList["location"].getLastData() if fix["lastFix"] == None: return "I don't know where you are" l = Location() l.name = 'gpsFix' l.region = 'gpsFix' l.latitude = float(fix["lastFix"]["lat"]) l.longitude = float(fix["lastFix"]["lon"]) l.timezone = self.tz.tzNameAt(float(fix["lastFix"]["lat"]),float(fix["lastFix"]["lon"])) l.elevation = float(fix["lastFix"]["alt"]) if "sunset" in words: return str(l.sunset().strftime("%-I:%M%P")) if "sunrise" in words: return str(l.sunrise().strftime("%-I:%M%P")) if "phase of the moon" in words: return str(l.moon_phase())
def test_Location_SunsetUTC(): c = Location() c.sunset(local=False)
def test_Location_Sunset(): c = Location() c.sunset()
class NightTime(Resource): isNightTime = False def __init__(self, name="NightTime", lat=None, lon=None, timezone="US/Pacific"): Resource.__init__( self, name, ["nightTime", "night_time", "sunset", "sunrise"]) if lat is None or lon is None: try: config = get_resource("ConfigurationResource") lat = config.get_value("latitude") lon = config.get_value("longitude") except ResourceNotFoundException: raise Exception( "NightTime requires lat/lon set or ConfigurationResource") if lat is None or lon is None: raise Exception( "NightTime: missing latitude/longitude in ConfigurationResource") print("using lat/lon: {}, {}".format(lat, lon)) self.location = Location() self.location.latitude = float(lat) self.location.longitude = float(lon) self.location.timezone = timezone self.process() self.poller = resource_poll(self.process, MINS(1)) def is_day(self): return not self.isNightTime @property def is_night(self): return self.isNightTime def process(self): t = datetime.now().time() try: current_time_resource = Resource.resource("CurrentTimeResource") has_time = current_time_resource.getValue("datetime") if has_time is not None: t = has_time.time() except ResourceNotFoundException: pass except Exception as e: print("night_time: another bad exception: {}".format(e)) self.isNightTime = ((t > self.location.sunset().time() and t <= time(23, 59, 59)) or (t >= time(0) and t < self.location.sunrise().time())) self.sunset = self.location.sunset().time() self.sunrise = self.location.sunrise().time() self.setValue("nightTime", self.isNightTime) self.setValue("night_time", self.isNightTime) self.setValue("sunset", str(self.location.sunset().time())) self.setValue("sunrise", str(self.location.sunrise().time()))
def adaptBrightnessToLocalDaytime(self): config = Configurations() # check whether sunrise/sunset can be defined by location if config.getAutoBrightnessMax() is not None and \ config.getAutoBrightnessMin() is not None and \ self.localCity is not None and \ self.localCountry is not None and \ self.localLat is not None and \ self.localLon is not None: # create Astral Location object for sunset/sunrise calculation # https://astral.readthedocs.io/en/stable/index.html astralLoc = Location(( self.localCity, self.localCountry, self.localLat, self.localLon, # local timezone, see https://stackoverflow.com/questions/2720319/python-figure-out-local-timezone '/'.join(os.path.realpath('/etc/localtime').split('/')[-2:]), # well, anyone has a lucky number? # based on https://www.quora.com/What-is-the-average-elevation-of-Earth-above-the-ocean-including-land-area-below-sea-level-What-is-the-atmospheric-pressure-at-that-elevation # "The average elevation of the land is 800m, covering 29% of the surface." # and https://ngdc.noaa.gov/mgg/global/etopo1_surface_histogram.html # "average land height: 797m" 500)) # ensure we are using the same timezone for all to compare sunrise = astralLoc.sunrise() sunset = astralLoc.sunset() now = datetime.datetime.now(sunrise.tzinfo) print( "Daytime brightness adaption started - now: {0}, sunrise: {1}, sunset: {2}, current brightness: {3}" .format(now, sunrise, sunset, self.getBrightness())) # check if night time if now < sunrise or now > sunset: # sleep mode in dark hours self.setBrightness(config.getAutoBrightnessMin()) # assure the fading process for brightness increase is started after sunrise within the boundaries of the update cycle elif now < sunrise + timedelta(seconds=self.UpdateFrequency): # see method description for initial parametrization fadeBrightness(self, self.getBrightness(), config.getAutoBrightnessMax(), 600, True) # assure the fading process for brightness decrease is started before sunset within the boundaries of the update cycle elif now > sunset - timedelta(seconds=self.UpdateFrequency): fadeBrightness(self, self.getBrightness(), config.getAutoBrightnessMin(), 600, True) else: # daytime mode self.setBrightness(config.getAutoBrightnessMax()) # use fixed times for fading brightness # check whether sunrise/sunset fading generally is activated - depends on definition of minBrightness elif config.getAutoBrightnessMin() is not None: now = datetime.datetime.now().time() print( "Daytime brightness adaption started - now: {0}, static, current brightness: {1}" .format(now, self.getBrightness())) if now > datetime.time(21, 0, 0) or now < datetime.time(6, 0, 0): # sleep mode in dark hours self.setBrightness(config.getAutoBrightnessMin()) else: # daytime mode self.setBrightness(config.getAutoBrightnessMax()) else: # ensure we have set the right brightness value, using maxBrightness if config.getAutoBrightnessMax() != self.getBrightness(): self.setBrightness(config.getAutoBrightnessMax())
from crontab import CronTab from datetime import datetime from astral import Location # Location info for sunrise and sun calculation info=( 'Brno', 'Czech Republic', 49.241921, 16.566693, 'Europe/Prague', 278 ) l=Location(info) # Calculate sunrise and sunset for current day brno_today_sunrise=l.sunrise(datetime.today().date(), True) brno_today_sunset=l.sunset(datetime.today().date(), True) # Open crontab file file_cron=CronTab(tabfile='crontab.txt') # Find open and close job in crontab and update # sunrise and sunset with calculated time for job in file_cron: if 'open command to window' in job.comment: job.hour.on(brno_today_sunrise.hour) job.minute.on(brno_today_sunrise.minute) elif 'close command to window' in job.comment: job.hour.on(brno_today_sunset.hour) job.minute.on(brno_today_sunset.minute) # Write changes to crontab file file_cron.write()