def change_mode(self): sun = Sun(self.latitude, self.longitude) sunrise = ''' tell application "System Events" tell appearance preferences set dark mode to false end tell end tell ''' sunset = ''' tell application "System Events" tell appearance preferences set dark mode to true end tell end tell ''' p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) today_sr = (sun.get_sunrise_time() - datetime.timedelta(hours=16)).strftime('%Y-%m-%d %H:%M') today_ss = (sun.get_sunset_time() + datetime.timedelta(hours=8)).strftime('%Y-%m-%d %H:%M') print(today_sr, today_ss) # 获取当前时间 now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') # 白天(不需要开暗黑模式) if today_sr < now < today_ss: p.communicate(sunrise) else: p.communicate(sunset) return
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 __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 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 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 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 update_sun_times(): try: sun = Sun(latitude, longitude) sunrise = sun.get_sunrise_time() sunset = sun.get_sunset_time() # Version for machine's local time # sunrise = sun.get_local_sunrise_time() # sunset = sun.get_local_sunset_time() light_turnOn = sunset + timedelta(minutes=20) light_turnOn_time = time(light_turnOn.hour, light_turnOn.minute, tzinfo=tz.tzutc()) light_turnOff = sunrise + timedelta(minutes=30) light_turnOff_time = time(light_turnOff.hour, light_turnOff.minute, tzinfo=tz.tzutc()) if (manualMode == True): if debug: print( "=== Sun times acquired, switching to sunrise/sunset mode ===" ) manualMode = False elif (manualMode == False): if debug: print("=== Sun times updated ===") return True except SunTimeException as e: if debug: print("SunTime failed. Error: {0}.".format(e)) print("!!! SWITCHING TO MANUAL TIME MODE !!!") manualMode = True return False
def get_suntimes(date, latitude=47.26, longitude=11.39): sun = Sun(latitude, longitude) # Get today's sunrise and sunset in UTC today_sr = sun.get_sunrise_time(date) today_ss = sun.get_sunset_time(date) return ({'sunrise': today_sr, 'sunset': today_ss})
class Suntime: # magic! OFFSET = timedelta(minutes=30) def __init__(self, location, logger): self.logger = logger self.sun = None if location is not None: self.sun = Sun(location[0], location[1]) def sunset(self, cur_date): sunset = self.sun.get_sunset_time(cur_date) return sunset - Suntime.OFFSET def sunrise(self, cur_date): sunrise = self.sun.get_sunrise_time(cur_date) return sunrise + Suntime.OFFSET def is_night(self, cur_date): if self.sun is None: return False sunrise = self.sunrise(cur_date) sunset = self.sunset(cur_date) if sunrise > sunset: if sunset <= cur_date <= sunrise: return True else: if sunrise <= cur_date <= sunset: return True
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 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 main(): print("LED Controller Starting...") GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18, GPIO.OUT) GPIO.output(18, GPIO.HIGH) while True: sun = Sun(latitude, longitude) sunrise = sun.get_sunrise_time() sunset = sun.get_sunset_time() print(sunrise) print(sunset) t = datetime.now(timezone.utc) print(t) seven_am = datetime.now(timezone.utc).replace(hour=6, minute=0, second=0, microsecond=0) if seven_am < t < sunset: print("Time is greater than sunrise but less than sunset") GPIO.output(18, GPIO.HIGH) else: print("Before Sunrise or after Sunset") GPIO.output(18, GPIO.LOW) time.sleep(60)
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 getSunsetTime(when=None): s = Sun(lat,lon) if when is None: when = datetime.datetime.now() sunsetToday = s.get_sunset_time(when) sunsetToday = sunsetToday + datetime.timedelta(days=1)# library has off by 1 day, unsure why ? ( known issue? ) print(f'Next sunset at: {sunsetToday.strftime('%m/%d/%y %H:%M')}') return sunsetToday
def __init__(self): lldic = medfordor.LOCATION(_)[0] self.sun = Sun(lldic.get('lat'), lldic.get('lon')) self.times = {} self.times['lsr'] = self.sun.get_Local_Sunrise_time() self.times['lss'] = self.sun.get_Local_Sunset_time() self.times['utcsr'] = sun.get_sunrise_time() self.times['utcss'] = sun.get_sunset_time()
def is_day(self): sun = Sun(self.lat, self.lng) sunrise, sunset = sun.get_sunrise_time(), sun.get_sunset_time() if sunset < sunrise: sunset += timedelta(days=1) now = datetime.now(timezone.utc) return (sunrise < now < sunset or sunrise < now + timedelta(days=1) < sunset or sunrise < now + timedelta(days=-1) < sunset)
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 __init__(self, config, theme): super().__init__(config, theme, core.widget.Widget(self.suntimes)) lat = self.parameter("lat", None) lon = self.parameter("lon", None) self.__sun = None if not lat or not lon: lat, lon = util.location.coordinates() if lat and lon: self.__sun = Sun(float(lat), float(lon))
def parse_config(self): ''' Method parsing config file or setting default values ''' with config.CONFIG_FILE.open(mode='r') as cf: config_dict = json.load(cf) self.wallpaper_dir = Path(config_dict['wallpaper_dir']) self.day_subdir = config_dict['day_subdir'] self.night_subdir = config_dict['night_subdir'] self.blurred_dir = Path(config_dict['blurred_dir']) self.interval = config_dict['interval'] self.sun = Sun(config_dict['latitude'], config_dict['longitude'])
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 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
class Daylight: def __init__(self): lldic = medfordor.LOCATION(_)[0] self.sun = Sun(lldic.get('lat'), lldic.get('lon')) self.times = {} self.times['lsr'] = self.sun.get_Local_Sunrise_time() self.times['lss'] = self.sun.get_Local_Sunset_time() self.times['utcsr'] = sun.get_sunrise_time() self.times['utcss'] = sun.get_sunset_time() def __str__(self): return f'{self.srt.date()}: SR: {self.srt.time()}, SS: {self.sst.time()}' def __repr__(self): return f'[Daylight: {self.srt.date()}: SR: {self.srt.time()}, SS: {self.sst.time()}]'
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 run_loop(base, pause, config): sun = Sun(config["latitude"], config["longitude"]) print("Pause : " + str(pause)) while True: # take_shot = sun.get_sunrise_time() < datetime.now(timezone.utc) < sun.get_sunset_time() take_shot = True ### For testing purposes at night if (take_shot == True): now = datetime.now() path = prepare_dir(base) name = str(datetime.now().year) + "_" + str( datetime.now().month).zfill(2) + "_" + str( datetime.now().day).zfill(2) + "_" + time.strftime( "%H") + "_" + time.strftime("%M") + ".jpg" print("Capturing " + name) file_name = base + "/" + path + "/" + name os_command = make_os_command(config, file_name) print(os_command) os.system(os_command) print("Written: " + file_name) else: print("Shot cancelled during hours of darkness") time.sleep(pause)
def get_sun(): lat = float(CONFIG['sun']['lat']) lon = float(CONFIG['sun']['lon']) logging.debug(f'Calculating sun dawn end down for LAT {lat}, LON {lon}') today = date.today() sun = Sun(lat, lon) return sun
def generate_pv_output(dt: datetime) -> int: """Wrapper to generate PV output. This gets the sunrise/sunset times for a given location and then invokes the actual PV calculation if the given datetime is inbetween the two times. If the given datetime is not between sunrise and sunset, 0 is returned instead. """ sun = Sun(LATITUDE, LONGITUDE) sunrise = sun.get_sunrise_time() sunset = sun.get_sunset_time() if not is_sunny(dt, sunrise, sunset): return 0 return calculate_pv_output(dt, sunrise, sunset)
def get_sun() -> Sun: """ Returns a configured sun class (with the local coordinates) """ latitude = 47.3816942 longitude = 8.4821749 sun = Sun(latitude, longitude) return sun
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 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)