def calc_location(): import geocoder from suntime import Sun, SunTimeException mygeo = geocoder.ip("me") print("lat:", mygeo.latlng[0]) print("lng:", mygeo.latlng[1]) sun = Sun(mygeo.latlng[0], mygeo.latlng[1]) # calculate the local sunrise and sunset c_sunrise = sun.get_local_sunrise_time() c_sunset = sun.get_local_sunset_time() print(c_sunrise.strftime("%H"), ":", c_sunrise.strftime("%M")) print(c_sunset.strftime("%H"), ":", c_sunset.strftime("%M")) #store the options from the calculation into the dictionary # the prog_options is already loaded. We call this from load_conf global prog_options # store the sunrise hour prog_options["light_hour"] = int(c_sunrise.strftime("%H")) # store the sunrise minute prog_options["light_minute"] = int(c_sunrise.strftime("%M")) # store the sunset hour prog_options["dark_hour"] = int(c_sunset.strftime("%H")) # store the sunset minute prog_options["dark_minute"] = int(c_sunset.strftime("%M"))
def sunset(): sun = Sun(latitude, longitude) ss = sun.get_local_sunset_time(local_time_zone=denver) sr = sun.get_local_sunrise_time(local_time_zone=denver) if ss < sr: ss = ss + timedelta(1) return ss.replace(tzinfo=None)
def recalc_door_times(time_control_config, for_day, min_after_sunrise, min_after_sunset): sun = Sun(time_control_config['latitude'], time_control_config['longitude']) door_times = {} door_times['sunrise_time'] = sun.get_local_sunrise_time(for_day) door_times['sunset_time'] = sun.get_local_sunset_time(for_day) if min_after_sunrise is None: door_times['sunrise_open_time'] = door_times['sunrise_time'] + \ datetime.timedelta(minutes=time_control_config['minutes_after_sunrise']) else: door_times['sunrise_open_time'] = door_times['sunrise_time'] + \ datetime.timedelta(minutes=min_after_sunrise) if min_after_sunset is None: door_times['sunset_close_time'] = door_times['sunset_time'] + \ datetime.timedelta(minutes=time_control_config['minutes_after_sunset']) else: door_times['sunset_close_time'] = door_times['sunset_time'] + \ datetime.timedelta(minutes=min_after_sunset) # print('sunrise: {0}'.format(sunrise_time.strftime('%H:%M'))) # print('sunset: {0}'.format(sunset_time.strftime('%H:%M'))) door_times_converted = {} for elem in door_times: if type(door_times[elem]) == datetime.datetime: door_times_converted[elem] = door_times[elem].strftime('%H:%M') else: door_times_converted[elem] = door_times[elem] return door_times, door_times_converted
def test_sunset(): irrigate, logger, cfg, valves, q = init("test_config.yaml") sun = Sun(cfg.latitude, cfg.longitude) nowTime = datetime.datetime.now() # + datetime.timedelta(seconds=10) timezone = cfg.timezone nowTime = nowTime.replace(tzinfo=pytz.timezone(timezone)) sunsetTime = sun.get_local_sunset_time().replace( tzinfo=pytz.timezone(timezone)) if (nowTime < sunsetTime): offset = sunsetTime - nowTime cfg.schedules['sched3'].start = "+" else: offset = nowTime - sunsetTime cfg.schedules['sched3'].start = "-" hours = offset.seconds // 60 // 60 minutes = (offset.seconds - (hours * 60 * 60)) // 60 cfg.schedules['sched3'].start = cfg.schedules['sched3'].start = "+" + str( hours) + ":" + str(minutes) cfg.schedules['sched3'].duration = 1 cfg.valves['valve4'].enabled = True cfg.valves['valve1'].schedules.clear() cfg.valves['valve2'].schedules.clear() cfg.valves['valve3'].schedules.clear() irrigate.start() assertValves(valves, ['valve4'], [(False, False)]) time.sleep(5) assertValves(valves, ['valve4'], [(True, True)])
def sun(): try: geolocator = Nominatim(user_agent="geoapiExercises") #get city from textbox entry ladd1 = str(ent.get()) locat1 = geolocator.geocode(ladd1) #latitude and longitude from location latitude = locat1.latitude longitude = locat1.longitude sun = Sun(latitude, longitude) #gets correct time time_zone = datetime.datetime.now() #get rise and set times sunR = sun.get_local_sunrise_time(time_zone) sunS = sun.get_local_sunset_time(time_zone) #sets rise and set times res_rise = sunR.strftime('%H:%M') res_set = sunS.strftime('%I:%M %p') #results 1 & 2 are set to the rise and set times result1.set(res_rise) result2.set(res_set) except: #error messages if nothing is entered result1.set("Oops!") result2.set("Enter a city and try again.")
def set_time_events_for_today(today=None): sun = Sun(lat=AussenlichtConfig.LATITUDE, lon=AussenlichtConfig.LONGITUDE) if today is None: today_sunrise = sun.get_local_sunrise_time() today_sunset = sun.get_local_sunset_time() else: today_sunrise = sun.get_local_sunrise_time(today) today_sunset = sun.get_local_sunset_time(today) TodaysTimes = TimeCache( sunrise=today_sunrise, sunset=today_sunset, midnight=today_sunset.replace(hour=23, minute=59), last_midnight=today_sunrise.replace(hour=0, minute=1), ) return TodaysTimes
def wait_for_event(waituntil): # wait until sunset/sunrise, assuming we have the info we need... mylatitude = os.getenv("MYLATITUDE", "") logging.debug("mylatitude..: '" + mylatitude + "'") mylongitude = os.getenv("MYLONGITUDE", "") logging.debug("mylongitude.: '" + mylongitude + "'") if mylatitude != "" and mylongitude != "": sun = Sun(float(mylatitude), float(mylongitude)) if waituntil == 'SUNRISE': runtime = sun.get_local_sunrise_time() else: runtime = sun.get_local_sunset_time() logging.info("Waiting until after '" + str(runtime) + "'...") mytimezone=runtime.tzinfo logging.debug("mytimezone..: '" + str(mytimezone) + "'") timenow = datetime.now(mytimezone) logging.debug("timenow.....: '" + str(timenow) + "'") while timenow < runtime: time.sleep(120) timenow = datetime.now(mytimezone) logging.debug("timenow.....: '" + str(timenow) + "'") logging.info("We can proceed...") else: logging.info("MYLATITUDE and MYLONGITUDE are unset, running NOW...")
def _calculate_times(self): self._isup = False try: if not self._lat or not self._lon: raise () sun = Sun(self._lat, self._lon) except Exception: self._sunrise = None self._sunset = None return order_matters = True try: self._sunrise = sun.get_local_sunrise_time() except SunTimeException: self._sunrise = "no sunrise" order_matters = False try: self._sunset = sun.get_local_sunset_time() except SunTimeException: self._sunset = "no sunset" order_matters = False if not order_matters: return now = datetime.datetime.now(tz=tzlocal()) if now > self._sunset: tomorrow = (now + datetime.timedelta(days=1)).date() try: self._sunrise = sun.get_local_sunrise_time(tomorrow) self._sunset = sun.get_local_sunset_time(tomorrow) except SunTimeException: self._sunrise = "no sunrise" self._sunset = "no sunset" elif now > self._sunrise: tomorrow = (now + datetime.timedelta(days=1)).date() try: self._sunrise = sun.get_local_sunrise_time(tomorrow) except SunTimeException: self._sunrise = "no sunrise" return self._isup = True
def nightlight_off(): global config global sunrise_job global sunset_job for target in config.nightlight_targets: eval(config.nightlight_targets_type + '_command(target, "off")') schedule.cancel_job(sunrise_job) geolocator = Nominatim(user_agent='myapplication') location = geolocator.geocode(config.location) sun = Sun(location.latitude, location.longitude) sunset = sun.get_local_sunset_time() do_sunset = sun.get_local_sunset_time() - timedelta(minutes=30) print(datetime.now(), 'Scheduling today sunset for', do_sunset.strftime('%H:%M')) sunset_job = schedule.every().day.at( do_sunset.strftime('%H:%M')).do(nightlight_on)
def getRiseAndSet(latitude, longitude): sun = Sun(latitude, longitude) today_sr = sun.get_local_sunrise_time() today_ss = sun.get_local_sunset_time() if TEST: print('Sunrise: {} Sunset: {} PDT'.format(today_sr.strftime('%H:%M'), today_ss.strftime('%H:%M'))) return [today_sr.time(), today_ss.time()]
def calculate_monthly_usage(lat, lon, power, y, m): daysInMonth = days_in_month(m, y) totalMonthlyUsage = 0 for i in range(daysInMonth): date_sun = Sun(lat, lon) time = datetime.date(year=y, month=m, day=i + 1) date_sunrise = date_sun.get_local_sunrise_time(time) date_sunset = date_sun.get_local_sunset_time(time) total_hours = datetime.timedelta(hours = 24) - (date_sunset - date_sunrise) totalMonthlyUsage += ((total_hours.total_seconds()) / 3600) * power return round(totalMonthlyUsage, 2)
def mySuntime(query): ''' #uncomment this section when online geo = geocoder.ip('me') latitude = geo.latlng[0] longitude= geo.latlng[1] ''' #this section for my own location latitude = 22.5837655 longitude = 90.2677207 ''' # get ipinfo from ipinfo.io #geo = geocoder.ip('me') if geocoder.ip('me').ok == False: latitude = 22.5837655 longitude = 90.2677207 else: geo = geocoder.ip('me') latitude = geo.latlng[0] longitude= geo.latlng[1] ''' sun = Sun(latitude, longitude) todaySr = sun.get_local_sunrise_time() todaySs = sun.get_local_sunset_time() sunRiseHour = int(todaySr.strftime('%H')) sunRiseMinute = int(todaySr.strftime('%M')) sunRiseAmPm = "AM" if sunRiseHour >= 12: sunRiseHour = sunRiseHour - 12 sunRiseAmPm = "PM" sunSetHour = int(todaySs.strftime('%H')) sunSetMinute = int(todaySs.strftime('%M')) sunSetAmPm = "AM" if sunSetHour >= 12: sunSetHour = sunSetHour - 12 sunSetAmPm = "PM" #return only sunrise time if query == 'sunrise': return f"todays sunrise time is {sunRiseHour} : {sunRiseMinute} : {sunRiseAmPm}" #return only sunset time elif query == 'sunset': return f"todays sunset time is {sunSetHour} : {sunSetMinute} : {sunSetAmPm}" #return both sunrise and sunset time elif query == 'sunrise and sunset' or query == 'sunset and sunrise': return f"todays sunrise time is {sunRiseHour} : {sunRiseMinute} : {sunRiseAmPm} and todays sunset time is {sunSetHour} : {sunSetMinute} : {sunSetAmPm}" #error message else: return 'opps the perfect query will be "sunris"/"sunset"/"sunrise and sunset"/"sunset and sunrise"'
def detail_city_weather_view(request, city): url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city + '&APPID=d15a8e835c366afc687227da39ceb337' r = requests.get(url.format(city)).json() sunrise = "" sunset = "" latitude = r['coord']['lat'] longitude = r['coord']['lon'] sun = Sun(latitude, longitude) dt = datetime.datetime.today() #to fix: local time sunrise and sunset, error with KeyError or favicon.ico #https://github.com/SatAgro/suntime try: sunrise = sun.get_local_sunrise_time(dt) sunset = sun.get_local_sunset_time() except SunTimeException as e: print("Error: {0}.".format(e)) weather_data = { 'city': city, 'country': r['sys']['country'], 'temperature': round((int(r['main']['temp']) - 273.15), 1), 'temperatureFeelsLike': round((int(r['main']['feels_like']) - 273.15), 1), 'mainDescription': r['weather'][0]['main'], 'icon': r['weather'][0]['icon'], 'datetime': datetime.datetime.now(), 'pressure': r['main']['pressure'], 'description': r['weather'][0]['description'], 'humidity': r['main']['humidity'], 'visibility': round((int(r['visibility']) / 1000), 1), 'tempMin': round((int(r['main']['temp_min']) - 273.15), 1), 'tempMax': round((int(r['main']['temp_max']) - 273.15), 1), 'wind': r['wind']['speed'], 'cloudiness': r['clouds']['all'], 'sunrise': sunrise, 'sunset': sunset, 'timezone': (int(r['timezone']) / 3600), } context = { 'weather_data': weather_data, } return render(request, 'weather/detail_city_weather.html', context)
def main(): global sunset_job global mqtt_client global config config = read_config('./minion.ini') mqtt_client.on_connect = on_connect mqtt_client.on_message = on_message mqtt_client.connect(config.mqtt_server, config.mqtt_port, 60) geolocator = Nominatim(user_agent='myapplication') location = geolocator.geocode(config.location) sun = Sun(location.latitude, location.longitude) sunset = sun.get_local_sunset_time() do_sunset = sun.get_local_sunset_time() - timedelta(minutes=30) print(datetime.now(), 'First sunset at', sunset.strftime('%H:%M')) print(datetime.now(), 'Scheduling today sunset for', do_sunset.strftime('%H:%M')) # Schedule nightlight events sunset_job = schedule.every().day.at( do_sunset.strftime('%H:%M')).do(nightlight_on) # Schedule goodnight # schedule.every().day.at(config.goodnight).do(goodnight) # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. while True: try: #asyncio.get_event_loop().run_until_complete(receive_deconz_messages()) mqtt_client.loop_forever() except KeyboardInterrupt: print(datetime.now(), "Exiting.") sys.exit()
def suntime_calculate_next_sunrise_sunset_epoch(latitude, longitude, date_offset_days, time_offset_minutes, rise_or_set, return_dt=False): try: from suntime import SunTimeException from suntime import Sun as SunTime sun = SunTime(latitude, longitude) now = datetime.datetime.now() new_date = now + datetime.timedelta(days=date_offset_days) new_date = new_date + datetime.timedelta(minutes=time_offset_minutes) if rise_or_set == 'sunrise': sunrise = sun.get_local_sunrise_time(new_date) if time_offset_minutes != 0: sunrise = sunrise + datetime.timedelta( minutes=time_offset_minutes) while sunrise.timestamp() > now.timestamp( ): # Find sunrise for yesterday sunrise = sunrise - datetime.timedelta( days=1) # Make sunrise tomorrow sunrise = sunrise + datetime.timedelta(days=1) if return_dt: return sunrise else: return float(sunrise.strftime('%s')) elif rise_or_set == 'sunset': sunset = sun.get_local_sunset_time(new_date) if time_offset_minutes != 0: sunset = sunset + datetime.timedelta( minutes=time_offset_minutes) while sunset.timestamp() > now.timestamp( ): # Find sunset for yesterday sunset = sunset - datetime.timedelta( days=1) # Make sunset tomorrow sunset = sunset + datetime.timedelta(days=1) if return_dt: return sunset else: return float(sunset.strftime('%s')) except SunTimeException: logger.exception("Generating next sunrise/sunset time") return except Exception: logger.exception("Generating next sunrise/sunset time") return
def set_sun_time(): latitude: float = float(get("latitude")) longitude: float = float(get("longitude")) sun = Sun(latitude, longitude) try: today_sr = sun.get_local_sunrise_time() today_ss = sun.get_local_sunset_time() # Get today's sunrise and sunset in UTC update("switchToLight", today_sr.strftime('%H:%M')) update("switchToDark", today_ss.strftime('%H:%M')) except SunTimeException as e: logger.error(f"Error: {e}.")
def _calculate_times(self): try: sun = Sun(self._lat, self._lon) except Exception: self._sunrise = None self._sunset = None return try: self._sunrise = sun.get_local_sunrise_time() except SunTimeException: self._sunrise = 'no sunrise' try: self._sunset = sun.get_local_sunset_time() except SunTimeException: self._sunset = 'no sunset'
def sun_is_up(date_and_time): date_and_time = date_and_time.replace(tzinfo=pytz.utc) latitude = 51.21 longitude = 4.42 sun = Sun(latitude, longitude) date = date_and_time.date() sunrise = sunset = 0 try: sunrise = sun.get_local_sunrise_time(date) sunset = sun.get_local_sunset_time(date) except SunTimeException as e: print("Error: {0}.".format(e)) return sunrise + datetime.timedelta( minutes=15) <= date_and_time <= sunset - datetime.timedelta(minutes=15)
def set_sun_time(): latitude: float = float(get("latitude")) longitude: float = float(get("latitude")) sun = Sun(latitude, longitude) try: today_sr = sun.get_local_sunrise_time() today_ss = sun.get_local_sunset_time() print('Today the sun raised at {} and get down at {}'. format(today_sr.strftime('%H:%M'), today_ss.strftime('%H:%M'))) # Get today's sunrise and sunset in UTC update("switchToLight", today_sr.strftime('%H:%M')) update("switchToDark", today_ss.strftime('%H:%M')) except SunTimeException as e: print("Error: {0}.".format(e))
def check_sunup(): # return 1 if it sun is currently up; 0 if not pst = pytz.timezone('US/Pacific') tnow = pst.localize(datetime.now()) lat = 40 lon = -120 # latitude and longitude sun = Sun(lat, lon) # Get today's sunrise and sunset Tdate = date.today() # datetime.date.today() is today's date today_sr = (sun.get_local_sunrise_time(Tdate)) today_ss = (sun.get_local_sunset_time(Tdate) ) # but might be yesterday's sunset if today_ss < today_sr: today_ss = today_ss + timedelta( 1) # account for non-UTC bug in suntime.Sun if (today_sr < tnow) and (tnow < today_ss): return 1 # The sun is now up else: return 0 # The sun is now down
def evalSched(self, sched, timezone, now): todayStr = calendar.day_abbr[datetime.today().weekday()] if not todayStr in sched.days: return False lat, lon = self.cfg.getLatLon() if sched.seasons != None and not self.getSeason(lat) in sched.seasons: return False hours, minutes = sched.start.split(":") startTime = datetime.now() if sched.type == 'absolute': startTime = startTime.replace(hour=int(hours), minute=int(minutes), second=0, microsecond=0, tzinfo=pytz.timezone(timezone)) else: sun = Sun(lat, lon) if sched.type == 'sunrise': startTime = sun.get_local_sunrise_time().replace( second=0, microsecond=0, tzinfo=pytz.timezone(timezone)) elif sched.type == 'sunset': startTime = sun.get_local_sunset_time().replace( second=0, microsecond=0, tzinfo=pytz.timezone(timezone)) if hours[0] == '+': hours = hours[1:] startTime = startTime + timedelta(hours=int(hours), minutes=int(minutes)) if hours[0] == '-': hours = hours[1:] startTime = startTime - timedelta(hours=int(hours), minutes=int(minutes)) if startTime == now: return True return False
def sun_rise_set(latitude, longitude, abd, TZ="UTC"): sun = Sun(latitude, longitude) if (TZ == "UTC"): today_sr = sun.get_sunrise_time() today_ss = sun.get_sunset_time() if DBG: print( 'Today at {2[0]}°{2[1]}\'{2[2]:2.2f}"N {2[3]}°{2[4]}\'{2[5]:2.2f}"E the sun raised at {0} and get down at {1} UTC' .format(today_sr.strftime('%H:%M:%S'), today_ss.strftime('%H:%M:%S'), coord(latitude, longitude))) return today_sr, today_ss else: abd_sr = sun.get_local_sunrise_time(abd) abd_ss = sun.get_local_sunset_time(abd) if DBG: print( 'On {0} the sun at {2[0]}°{2[1]}\'{2[2]:2.2f}\"N {2[3]}°{2[4]}\'{2[5]:2.2f}\"E raised at {1} and get down at {3}.' .format(abd, abd_sr.strftime('%H:%M:%S'), coord(latitude, longitude), abd_ss.strftime('%H:%M:%S'))) return abd_sr, abd_ss
def getglobalvar(varname): global SysVars, suntimesupported svname = varname.strip().lower() par = "" if ("-" in svname): resarr = svname.split("-") svname = resarr[0] par = "-"+resarr[1] if ("+" in svname): resarr = svname.split("+") svname = resarr[0] par = "+"+resarr[1] res = "" if svname in SysVars: if svname==SysVars[0]: #%systime% 01:23:54 return datetime.now().strftime('%H:%M:%S') elif svname==SysVars[1]: #%systm_hm% 01:23 return datetime.now().strftime('%H:%M') elif svname==SysVars[2]: #%lcltime% 2018-03-16 01:23:54 return datetime.now().strftime('%Y-%m-%d %H:%M:%S') elif svname==SysVars[3]: #%syshour% 11 Current hour (hh) return int(datetime.now().strftime('%H')) elif svname==SysVars[4]: #%sysmin% 22 Current minute (mm) return int(datetime.now().strftime('%M')) elif svname==SysVars[5]: #%syssec% 33 Current second (ss) return int(datetime.now().strftime('%S')) elif svname==SysVars[6]: #%sysday% 16 Current day of month (DD) return int(datetime.now().strftime('%d')) elif svname==SysVars[7]: #%sysmonth% 3 Current month (MM) return int(datetime.now().strftime('%m')) elif svname==SysVars[8]: #%sysyear% 2018 4 digits (YYYY) return datetime.now().strftime('%Y') elif svname==SysVars[9]: #%sysyears% 18 2 digits (YY) return datetime.now().strftime('%y') elif svname==SysVars[10]: #%sysweekday% 5 Weekday (integer) - 1, 2, 3... (1=Sunday, 2=Monday etc.) return str(int(datetime.now().strftime('%w'))+1) elif svname==SysVars[11]: #%sysweekday_s% Fri Weekday (verbose) - Sun, Mon, Tue return datetime.now().strftime('%a') elif svname==SysVars[12]: #%unixtime% 1521731277 Unix time (seconds since epoch, 1970-01-01 00:00:00) return str(int(time.time())) elif svname==SysVars[13]: #%uptime% 3244 Uptime in minutes return str(rpieTime.getuptime(2)) elif svname==SysVars[14]: #%rssi% -45 WiFi signal strength (dBm) return str(OS.get_rssi()) elif svname==SysVars[15]: #%ip% 192.168.0.123 Current IP address return str(OS.get_ip()) elif svname==SysVars[16]: #%ip4% ipcim 4.byte res2 = str(OS.get_ip()) resarr = res2.split(".") if len(resarr)>3: return resarr[3] elif svname==SysVars[17]: #%sysname% name return Settings.Settings["Name"] elif svname==SysVars[18]: #%unit% 32 Unit number return Settings.Settings["Unit"] elif svname==SysVars[19]: #%ssid% H4XX0R njietwork! wdev = False try: wdev = Settings.NetMan.getfirstwirelessdev() except: wdev = False if wdev: res = str(Network.get_ssid(wdev)) elif svname==SysVars[20]: #%mac% 00:14:22:01:23:45 MAC address pd = -1 try: pd = Settings.NetMan.getprimarydevice() except: pd = -1 if pd<0 and len(Settings.NetworkDevices)>0: pd = 0 if pd!="" and pd>=0: return Settings.NetworkDevices[pd].mac elif svname==SysVars[21]: #%mac_int% 2212667 MAC address in integer to be used in rules (only the last 24 bit) pd = -1 try: pd = Settings.NetMan.getprimarydevice() except: pd = -1 if pd<0 and len(Settings.NetworkDevices)>0: pd = 0 if pd>=0: try: res2 = Settings.NetworkDevices[pd].mac resarr = res2.split(":") if len(resarr)>5: res = str(int("0x"+resarr[3]+resarr[4]+resarr[5],16)) except: res = "" return res elif svname==SysVars[22]: #%build% bstr = str(rpieGlobals.BUILD) return bstr elif svname==SysVars[23]: #sunrise try: from suntime import Sun suntimesupported = 1 except: suntimesupported = 0 if suntimesupported==1: try: sun = Sun(Settings.AdvSettings["Latitude"],Settings.AdvSettings["Longitude"]) abd_sr = sun.get_local_sunrise_time(datetime.now()) if par!="": abd_sr = addtoTime(abd_sr,par) res = abd_sr.strftime('%H:%M') except Exception as e: res = "00:00" return res elif svname==SysVars[24]: #sunset try: from suntime import Sun suntimesupported = 1 except: suntimesupported = 0 if suntimesupported==1: try: sun = Sun(Settings.AdvSettings["Latitude"],Settings.AdvSettings["Longitude"]) abd_ss = sun.get_local_sunset_time(datetime.now()) if par!="": abd_ss = addtoTime(abd_ss,par) res = abd_ss.strftime('%H:%M') except Exception as e: res = "00:00" return res elif svname==SysVars[25]: #sun altitude try: from pytz import reference from pysolar.solar import get_altitude pysolarsupported = 1 except: pysolarsupported = 0 res = "0" if pysolarsupported==1: try: localtime = reference.LocalTimezone() today = datetime.now(localtime) res = get_altitude(Settings.AdvSettings["Latitude"],Settings.AdvSettings["Longitude"], today) except Exception as e: print(e) res = "0" return res elif svname==SysVars[26]: #sun azimuth try: from pytz import reference from pysolar.solar import get_azimuth pysolarsupported = 1 except: pysolarsupported = 0 res = "0" if pysolarsupported==1: try: localtime = reference.LocalTimezone() today = datetime.now(localtime) res = get_azimuth(Settings.AdvSettings["Latitude"],Settings.AdvSettings["Longitude"], today) except Exception as e: print(e) res = "0" return res elif svname==SysVars[27]: #sun radiation try: from pytz import reference from pysolar.solar import get_altitude from pysolar.radiation import get_radiation_direct pysolarsupported = 1 except: pysolarsupported = 0 res = "-1" if pysolarsupported==1: try: localtime = reference.LocalTimezone() today = datetime.now(localtime) altitude_deg = get_altitude(Settings.AdvSettings["Latitude"],Settings.AdvSettings["Longitude"], today) res = get_radiation_direct(today, altitude_deg) except Exception as e: print(e) return res elif svname==SysVars[28]: #%br% return str("\r\n") elif svname==SysVars[29]: #%lf% return str("\n") elif svname==SysVars[30]: #%tab% return str(" ") return res
def get_sunstuff(location): geolocator = Nominatim(user_agent='myapplication') location = geolocator.geocode(location) sun = Sun(location.latitude, location.longitude) return SunStuff(sun.get_local_sunrise_time(), sun.get_local_sunset_time())
import datetime from suntime import Sun, SunTimeException # Lyon latitude = 45.75 longitude = 4.85 sun = Sun(latitude, longitude) # Get today's sunrise and sunset in UTC today_sr = sun.get_sunrise_time() today_ss = sun.get_sunset_time() print('Today at Lyon the sun raised at {} and get down at {} UTC'.format( today_sr.strftime('%H:%M'), today_ss.strftime('%H:%M'))) # On a special date in your machine's local time zone abd = datetime.date(2020, 9, 25) abd_sr = sun.get_local_sunrise_time(abd) abd_ss = sun.get_local_sunset_time(abd) print( 'On {} the sun at Lyon raised at {} and get down at {}. local time'.format( abd, abd_sr.strftime('%H:%M'), abd_ss.strftime('%H:%M')))
while True: # if none of capture scenarios work, sleep 1min if Config.init_delay_idle: print("Idling {}".format(Config.delay_idle)) time.sleep(Config.delay_idle) d = datetime.datetime.now() # Capture current time concat_d = concat_2_int(d.hour, d.minute) # concat time Config.init_delay_idle = True # if there are no capture slots, sleep a wee (to save energy) # set correct capture scenario if user_settings.CAPTURE_SUN_TIME: # SUN_TIME has priority sun = Sun(user_settings.CAPTURE_SUN_TIME_LATITUDE, user_settings.CAPTURE_SUN_TIME_LONGITUDE) sunrise = sun.get_local_sunrise_time()+datetime.timedelta(minutes=user_settings.CAPTURE_SUN_TIME_SUNRISE_OFFSET) sunset = sun.get_local_sunset_time()+datetime.timedelta(minutes=user_settings.CAPTURE_SUN_TIME_SUNSET_OFFSET) if not user_settings.CAPTURE_SUN_TIME_NIGHTLY: # sunrise-sunset if concat_d >= sunrise.strftime('%H%M'): if concat_d <= sunset.strftime('%H%M'): capture("suntime") else: # sunset-sunrise if concat_d >= sunset.strftime('%H%M'): capture("suntime-overnight") elif concat_d <= sunrise.strftime('%H%M'): capture("suntime-overnight") else: for timeframe in user_settings.CAPTURE_TIMEFRAME: # is SUN_TIME is turned off, check CAPTURE_TIMEFRAME array concat_timeframe_start = concat_2_int(timeframe[0], timeframe[1]) concat_timeframe_end = concat_2_int(timeframe[2], timeframe[3])
def sunset(lat, long): todays_date = datetime.date.today() sun = Sun(lat, long) sunset = sun.get_local_sunset_time(todays_date).strftime('%H.%M') return sunset
from datetime import datetime, timezone, timedelta from suntime import Sun, SunTimeException latitude = 51.976132 longitude = 5.670997 sun = Sun(latitude, longitude) # Get today's sunrise and sunset in UTC today_sr = sun.get_local_sunrise_time() today_ss = sun.get_local_sunset_time() print('Today in Wageningen the sun rises at {} and sets at {}'.format( today_sr.strftime('%H:%M'), today_ss.strftime('%H:%M'))) # On a special date in your machine's local time zone print(datetime.now()) print(sun.get_local_sunrise_time(datetime.now() + timedelta(days=1))) print(sun.get_local_sunset_time(datetime.now() + timedelta(days=-1))) # Error handling (no sunset or sunrise on given location) #latitude = 87.55 #longitude = 0.1 #sun = Sun(latitude, longitude) #try: # abd_sr = sun.get_local_sunrise_time(abd) # abd_ss = sun.get_local_sunset_time(abd) # print('On {} at somewhere in the north the sun raised at {} and get down at {}.'. # format(abd, abd_sr.strftime('%H:%M'), abd_ss.strftime('%H:%M'))) #except SunTimeException as e: # print("Error: {0}.".format(e))
while True: #NTNU Gløshaugen sine koordinater latitude = 63.418 longitude = 10.406 sunproduction = 0 sun = Sun(latitude, longitude) # Nåværende tid today = datetime.today() d1 = today.strftime("%d.%m.%Y") # Finner ut av når solen står opp og går ned sunrise = sun.get_local_sunrise_time(today) sunset = sun.get_local_sunset_time(today) print ("Sunrise at ", sunrise.strftime( "%H:%M")) print ("Sunset at", sunset.strftime( "%H:%M")) suntime = (sunset-sunrise) print(suntime, "timer er solen oppe i løpet av en hel dag") sun_mid = (suntime/2) suntop = sun_mid + sunrise suntop = suntop.strftime("%Y-%m-%d %H:%M:%S") print("Solen er på sitt høyeste", suntop) """ Henter værdata fra metno! """
class Light(object): """reports sunrise and sunset times""" def __init__(self, location, lat, long, sunrise_delay, sunset_delay): self.location = location self.lat = lat self.long = long self.sunrise_delay = sunrise_delay self.sunset_delay = sunset_delay self.sun = Sun(lat, long) def sunrise(self, dt=None): """returns today's sunrise in local time""" return self.sun.get_local_sunrise_time(dt) def open_door(self, dt=None): """returns today's sunrise in local time + sunrise_delay """ return self.sunrise(dt) + timedelta(minutes=self.sunrise_delay) def sunset(self, dt=None): """returns today's sunset in local time""" ss = self.sun.get_local_sunset_time(dt) sr = self.sun.get_local_sunrise_time(dt) if ss < sr: tomorrow = datetime.now().astimezone(to_zone) + timedelta(1) ss = self.sun.get_local_sunset_time(tomorrow) return ss def close_door(self, dt=None): """returns today's sunset in local time + sunset_delay""" return self.sunset(dt) + timedelta(minutes=self.sunset_delay) def is_dark(self, dt=None): now = datetime.now().astimezone(to_zone) if dt: now = dt od = self.open_door(dt) cd = self.close_door(dt) if od < now < cd: return False return True def is_light(self, dt=None): return not self.is_dark(dt) def report(self, dt=None): """returns a report string""" sr = self.sunrise(dt) od = self.open_door(dt) ss = self.sunset(dt) cd = self.close_door(dt) now = datetime.now().astimezone(to_zone) if dt: now = dt logging.debug("Light:Now:%s", now.strftime(config.TIME_FORMAT)) logging.debug("Light:Sunrise:%s", sr.strftime(config.TIME_FORMAT)) logging.debug("Light:Open door:%s", od.strftime(config.TIME_FORMAT)) logging.debug("Light:Sunset:%s", ss.strftime(config.TIME_FORMAT)) logging.debug("Light:Close door:%s", cd.strftime(config.TIME_FORMAT)) if self.is_dark(dt): text = f"It is dark now in {self.location}. " else: text = f"It is daylight now in {self.location}. " # sunrise hasn't happened yet if now < sr: text += f"The sun will rise at {sr.strftime(config.TIME_FORMAT)}" if sr == od: text += " and it should be light enough to open the doors. " else: text += f" and it will be light enough to open the doors at {od.strftime(config.TIME_FORMAT)}. " # sunset has not yet happened elif now < ss: text += f"The sun rose at {sr.strftime(config.TIME_FORMAT)} and will set at {ss.strftime(config.TIME_FORMAT)}" if ss == cd: text += " and it should be dark enough to close the doors. " else: text += f" and it will be dark enough to close the doors at {cd.strftime(config.TIME_FORMAT)}. " # sunset already happened else: text += f"The sun set at {ss.strftime(config.TIME_FORMAT)}" if ss == cd: text += " and it should be dark enough to close the doors. " elif now < cd: text += f" and it will be dark enough to close the doors at {cd.strftime(config.TIME_FORMAT)}. " else: text += f" and it was dark enough to close the doors at {cd.strftime(config.TIME_FORMAT)}. " tomorrow = datetime.now().astimezone(to_zone) + timedelta(1) srt = self.sunrise(tomorrow) text += f"Tomorrow's sunrise is at {srt.strftime(config.TIME_FORMAT)}. " logging.info("Report:%s", text) return text