def __init__(self): self.hardware = Hardware() a = Astral() a.solar_depression = 'civil' self.city = a['Kiev'] self.rpc_server = RPCServer(self.hardware) self.rpc_server.start()
def getCorrectBackground(self): if self.Weather == None: return "day-sunny" city_name = 'London' a = Astral() a.solar_depression = 'civil' city = a[city_name] now = datetime.datetime.utcnow().replace(tzinfo=utc) sun = city.sun(date=datetime.datetime.now(), local=True) if now < sun['dawn']: #night return self.getNightBackground() elif now < sun['sunrise']: #sunrise return self.getSunSetRiseBackground() elif now < sun['sunset']: #day return self.getDayBackground() elif now < sun['dusk']: #sunset return self.getSunSetRiseBackground() else: #night return self.getNightBackground()
def ics(): astral = Astral() astral.solar_depression = "civil" astral.depression = 6.0 city = astral["Toronto"] cal = Calendar() cal.add("prodid", "-//Time of Day//time-of-day.herokuapp.com//") cal.add("version", "2.0") today = datetime.date.today() for x in range(-7, 8): date = today + datetime.timedelta(days=x) sun = city.sun(date=date, local=True) for summary, time in sun.items(): event = Event() event.add("summary", summary.capitalize()) event.add("dtstart", time) event.add("dtend", time) event.add("dtstamp", time) cal.add_component(event) resp = make_response(cal.to_ical()) resp.headers["Content-Disposition"] = "attachment; filename=time-of-day.ics" resp.headers["Content-Type"] = "text/calendar" return resp
def get_astral_data(for_datetime): ''' Returns the sunrise and sunset times for the given date. Uses the Astral package to compute sunrise/sunset for the configured city. Reference https://pythonhosted.org/astral/module.html :param for_datetime: :return: Returns a dict containing the keys sunrise and sunset. The values are datetime objects. ''' a = Astral() a.solar_depression = "civil" # We use a city just to get a city object. Then we override the lat/long. # The city object can produce sunrise/sunset in local time. if Configuration.City() != "": city = a[Configuration.City()] else: # Default if no city is configured city = a["New York"] if Configuration.Latitude() != "": city.latitude = float(Configuration.Latitude()) if Configuration.Longitude() != "": city.longitude = float(Configuration.Longitude()) return city.sun(date=for_datetime, local=True)
def getSolarInfo(): a = Astral() a.solar_depression = 'civil' city = a['Seattle'] timezone = city.timezone sun = city.sun(date=datetime.datetime.now()) return sun
def test_Astral_TimeAtElevation_SunSetting(): a = Astral() l = a['London'] d = datetime.date(2016, 1, 4) dt = a.time_at_elevation_utc(14, SUN_SETTING, d, l.latitude, l.longitude) cdt = datetime.datetime(2016, 1, 4, 13, 20, 0, tzinfo=pytz.UTC) assert datetime_almost_equal(dt, cdt, 300)
def test_Astral_TimeAtElevation_SunRisingBelowHorizon(): a = Astral() l = a['London'] d = datetime.date(2016, 1, 4) dt = a.time_at_elevation_utc(-18, SUN_RISING, d, l.latitude, l.longitude) cdt = datetime.datetime(2016, 1, 4, 6, 0, 0, tzinfo=pytz.UTC) assert datetime_almost_equal(dt, cdt, 300)
def test_Astral_TimeAtElevation_GreaterThan180(): a = Astral() l = a['London'] d = datetime.date(2015, 12, 1) dt = a.time_at_elevation_utc(186, SUN_RISING, d, l.latitude, l.longitude) cdt = datetime.datetime(2015, 12, 1, 16, 34, tzinfo=pytz.UTC) assert datetime_almost_equal(dt, cdt, 300)
def seconds_till_daytime_ends(lat,lon,delta_minutes): if not is_it_daytime(lat,lon,delta_minutes): return 0 now = datetime.now(UTC()) astral = Astral() sunset = astral.sunset_utc(now,lat,lon) - timedelta(minutes=delta_minutes) answer = int((sunset-now).total_seconds())+1 return answer
def test_Astral_SolarNoon(): dd = Astral() dt = datetime.datetime(2017, 2, 10) noon = dd.solar_noon_utc(dt, 49.65) assert noon.hour == 8 assert noon.minute == 55 assert noon.second == 37
def graph_values(diff_array): graph_data = [] graph_dates = [] sum_value = 0 index = 0 current_hour = plot_dates[0].hour sun_indexes = [] city_name = 'Stockholm' a = Astral() a.solar_depression = 'civil' city = a[city_name] sun = city.sun(plot_dates[0], local=True) graph_dates.append(plot_dates[0].strftime('%Y-%m-%d %H:%M:%S')) if (plot_dates[index].hour >= sun['sunrise'].hour and plot_dates[index].hour <= sun['sunset'].hour): sun_indexes.append(1) else: sun_indexes.append(0) for data in diff_array: if (plot_dates[index].hour > current_hour): graph_data.append(sum_value) sum_value = 0 sum_value = sum_value + int(data) current_hour = current_hour + 1 if (plot_dates[index].hour >= sun['sunrise'].hour and plot_dates[index].hour <= sun['sunset'].hour): sun_indexes.append(1) else: sun_indexes.append(0) graph_dates.append(plot_dates[index].strftime('%Y-%m-%d %H:%M:%S')) elif (plot_dates[index].hour < current_hour): graph_data.append(sum_value) sum_value = 0 sum_value = sum_value + int(data) current_hour = plot_dates[index].hour sun = city.sun(plot_dates[index], local=True) if (plot_dates[index].hour >= sun['sunrise'].hour and plot_dates[index].hour <= sun['sunset'].hour): sun_indexes.append(1) else: sun_indexes.append(0) graph_dates.append(plot_dates[index].strftime('%Y-%m-%d %H:%M:%S')) else: sum_value = sum_value + int(data) index = index + 1 graph_data.append(sum_value) return graph_dates, graph_data, sun_indexes
class plugin: ''' A class to display the time of sunrise/sunset Uses the astral library to retrieve information... ''' def __init__(self, config): ''' Initializations for the startup of the weather forecast ''' # Get plugin name (according to the folder, it is contained in) self.name = os.path.dirname(__file__).split('/')[-1] self.astral_at_location = Astral()[config.get('plugin_' + self.name, 'location')] # Choose language to display sunrise language = config.get('plugin_time_default', 'language') if language == 'german': self.taw = wcp_time_german.time_german() elif language == 'dutch': self.taw = wcp_time_dutch.time_dutch() elif language == 'swiss_german': self.taw = wcp_swiss_german.time_swiss_german() else: print('Could not detect language: ' + language + '.') print('Choosing default: german') self.taw = wcp_time_german.time_german() self.bg_color_index = 0 # default background color: black self.word_color_index = 2 # default word color: warm white self.minute_color_index = 2 # default minute color: warm white def run(self, wcd, wci): ''' Displaying current time for sunrise/sunset ''' # Get data of sunrise sun_data = self.astral_at_location.sun(date=datetime.datetime.now(), local=True) # Display data of sunrise wcd.animate(self.name, 'sunrise', invert=True) wcd.setColorToAll(wcc.colors[self.bg_color_index], includeMinutes=True) taw_indices = self.taw.get_time(sun_data['sunrise'], withPrefix=False) wcd.setColorBy1DCoordinates(wcd.strip, taw_indices, wcc.colors[self.word_color_index]) wcd.show() time.sleep(3) # Display data of sunset wcd.animate(self.name, 'sunrise') wcd.setColorToAll(wcc.colors[self.bg_color_index], includeMinutes=True) taw_indices = self.taw.get_time(sun_data['sunset'], withPrefix=False) wcd.setColorBy1DCoordinates(wcd.strip, taw_indices, wcc.colors[self.word_color_index]) wcd.show() time.sleep(3) # Display current moon phase moon_phase = int(self.astral_at_location.moon_phase(datetime.datetime.now())) for i in range(0, moon_phase): wcd.showIcon('sunrise', 'moon_'+str(i).zfill(2)) time.sleep(0.1) time.sleep(3)
async def test_track_sunrise_update_location(hass): """Test track the sunrise.""" # Setup sun component hass.config.latitude = 32.87336 hass.config.longitude = 117.22743 assert await async_setup_component( hass, sun.DOMAIN, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}} ) # Get next sunrise astral = Astral() utc_now = datetime(2014, 5, 24, 12, 0, 0, tzinfo=dt_util.UTC) utc_today = utc_now.date() mod = -1 while True: next_rising = astral.sunrise_utc( utc_today + timedelta(days=mod), hass.config.latitude, hass.config.longitude ) if next_rising > utc_now: break mod += 1 # Track sunrise runs = [] with patch("homeassistant.util.dt.utcnow", return_value=utc_now): async_track_sunrise(hass, lambda: runs.append(1)) # Mimick sunrise _send_time_changed(hass, next_rising) await hass.async_block_till_done() assert len(runs) == 1 # Move! with patch("homeassistant.util.dt.utcnow", return_value=utc_now): await hass.config.async_update(latitude=40.755931, longitude=-73.984606) await hass.async_block_till_done() # Mimick sunrise _send_time_changed(hass, next_rising) await hass.async_block_till_done() # Did not increase assert len(runs) == 1 # Get next sunrise mod = -1 while True: next_rising = astral.sunrise_utc( utc_today + timedelta(days=mod), hass.config.latitude, hass.config.longitude ) if next_rising > utc_now: break mod += 1 # Mimick sunrise at new location _send_time_changed(hass, next_rising) await hass.async_block_till_done() assert len(runs) == 2
def test_track_sunset(self): """Test track the sunset.""" latitude = 32.87336 longitude = 117.22743 # Setup sun component self.hass.config.latitude = latitude self.hass.config.longitude = longitude setup_component(self.hass, sun.DOMAIN, { sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) # Get next sunrise/sunset astral = Astral() utc_now = datetime(2014, 5, 24, 12, 0, 0, tzinfo=dt_util.UTC) utc_today = utc_now.date() mod = -1 while True: next_setting = (astral.sunset_utc( utc_today + timedelta(days=mod), latitude, longitude)) if next_setting > utc_now: break mod += 1 # Track sunset runs = [] with patch('homeassistant.util.dt.utcnow', return_value=utc_now): unsub = track_sunset(self.hass, lambda: runs.append(1)) offset_runs = [] offset = timedelta(minutes=30) with patch('homeassistant.util.dt.utcnow', return_value=utc_now): unsub2 = track_sunset( self.hass, lambda: offset_runs.append(1), offset) # Run tests self._send_time_changed(next_setting - offset) self.hass.block_till_done() self.assertEqual(0, len(runs)) self.assertEqual(0, len(offset_runs)) self._send_time_changed(next_setting) self.hass.block_till_done() self.assertEqual(1, len(runs)) self.assertEqual(0, len(offset_runs)) self._send_time_changed(next_setting + offset) self.hass.block_till_done() self.assertEqual(1, len(runs)) self.assertEqual(1, len(offset_runs)) unsub() unsub2() self._send_time_changed(next_setting + offset) self.hass.block_till_done() self.assertEqual(1, len(runs)) self.assertEqual(1, len(offset_runs))
def get_sunrise_sunset(): city = 'San Francisco' a = Astral() a.solar_depression = 'civil' city = a[city] sun = city.sun(date=datetime.now(), local=True) if now() >= sun['sunset']: sun = city.sun(date=datetime.now()+timedelta(days=1), local=True) return sun['sunrise'], sun['sunset']
def draw_astronomical(city_name, geo_data): datetime_day_start = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) a = Astral() a.solar_depression = 'civil' city = Location() city.latitude = geo_data["latitude"] city.longitude = geo_data["longitude"] city.timezone = geo_data["timezone"] answer = "" moon_line = "" for time_interval in range(72): current_date = (datetime_day_start + datetime.timedelta(hours=1 * time_interval)).replace( tzinfo=pytz.timezone(geo_data["timezone"])) sun = city.sun(date=current_date, local=False) dawn = sun['dawn'] # .replace(tzinfo=None) dusk = sun['dusk'] # .replace(tzinfo=None) sunrise = sun['sunrise'] # .replace(tzinfo=None) sunset = sun['sunset'] # .replace(tzinfo=None) if current_date < dawn: char = " " elif current_date > dusk: char = " " elif dawn < current_date and current_date < sunrise: char = u"─" elif sunset < current_date and current_date < dusk: char = u"─" elif sunrise < current_date and current_date < sunset: char = u"━" answer += char # moon if time_interval % 3 == 0: moon_phase = city.moon_phase( date=datetime_day_start + datetime.timedelta(hours=time_interval)) moon_phase_emoji = constants.MOON_PHASES[ int(math.floor(moon_phase * 1.0 / 28.0 * 8 + 0.5)) % len(constants.MOON_PHASES)] if time_interval in [0, 24, 48, 69]: moon_line += moon_phase_emoji + " " else: moon_line += " " answer = moon_line + "\n" + answer + "\n" answer += "\n" return answer
def seconds_till_daytime(lat,lon,delta_minutes): if is_it_daytime(lat,lon,delta_minutes): return 0 now = datetime.now(UTC()) astral = Astral() sunrise = astral.sunrise_utc(now,lat,lon) + timedelta(minutes=delta_minutes) if sunrise < now: sunrise = astral.sunrise_utc(now + timedelta(hours=23),lat,lon) + timedelta(minutes=delta_minutes) return int((sunrise-now).total_seconds())+1
def sunset(): city_name = 'Minneapolis' a = Astral() a.solar_depression = 'civil' city = a[city_name] sun = city.sun(date=datetime.datetime.now(), local=True) return 'Sunset for {}: {}'.format(city_name, sun['sunset'])
def sunrise_time(): from astral import Astral astr_object = Astral() astr_object.solar_depression = "civil" try: return astr_object[CITY].sun(local=True)["sunrise"] except Exception as error: ErrorWriter.write_error(error) return None
def test_Astral_TimeAtElevation_SunRising(): a = Astral() l = a['London'] d = datetime.date(2016, 1, 4) dt = a.time_at_elevation_utc(6, SUN_RISING, d, l.latitude, l.longitude) cdt = datetime.datetime(2016, 1, 4, 9, 5, 0, tzinfo=pytz.UTC) # Use error of 5 minutes as website has a rather coarse accuracy assert datetime_almost_equal(dt, cdt, 300)
def test_track_sunrise(self): """Test track the sunrise.""" latitude = 32.87336 longitude = 117.22743 # Setup sun component self.hass.config.latitude = latitude self.hass.config.longitude = longitude setup_component(self.hass, sun.DOMAIN, {sun.DOMAIN: { sun.CONF_ELEVATION: 0 }}) # Get next sunrise/sunset astral = Astral() utc_now = dt_util.utcnow() mod = -1 while True: next_rising = (astral.sunrise_utc(utc_now + timedelta(days=mod), latitude, longitude)) if next_rising > utc_now: break mod += 1 # Track sunrise runs = [] unsub = track_sunrise(self.hass, lambda: runs.append(1)) offset_runs = [] offset = timedelta(minutes=30) unsub2 = track_sunrise(self.hass, lambda: offset_runs.append(1), offset) # run tests self._send_time_changed(next_rising - offset) self.hass.block_till_done() self.assertEqual(0, len(runs)) self.assertEqual(0, len(offset_runs)) self._send_time_changed(next_rising) self.hass.block_till_done() self.assertEqual(1, len(runs)) self.assertEqual(0, len(offset_runs)) self._send_time_changed(next_rising + offset) self.hass.block_till_done() self.assertEqual(2, len(runs)) self.assertEqual(1, len(offset_runs)) unsub() unsub2() self._send_time_changed(next_rising + offset) self.hass.block_till_done() self.assertEqual(2, len(runs)) self.assertEqual(1, len(offset_runs))
def render_moonphase(_, query): """ A symbol describing the phase of the moon """ astral = Astral() moon_index = int( int(32.0*astral.moon_phase(date=datetime.datetime.today())/28+2)%32/4 ) return MOON_PHASES[moon_index]
def get_sun(date="today", depression="astronomical", cityname="Boston"): astral = Astral() astral.solar_depression = depression city = astral[cityname] calendar = parsedatetime.Calendar() dateinfo = calendar.parse(date) date_ts = time.mktime(dateinfo[0]) date_dt = datetime.fromtimestamp(date_ts) return city.sun(date=date_dt, local=True)
def api_v1(): astral = Astral() astral.solar_depression = "civil" astral.depression = 6.0 city = astral["Toronto"] response = { "is_day": False, "is_night": False, "is_civil_twlight": False, "is_nautical_twlight": False, "is_astronomical_twilight": False, "is_blue_hour": False, "is_golden_hour": False, "solar_zenith_angle": city.solar_zenith(), "solar_elevation_angle": city.solar_elevation(), "solar_azimuth_angle": city.solar_azimuth(), "times_of_day": city.sun(), } current_datetime = datetime.datetime.now(city.tz) if city.sunrise() < current_datetime < city.sunset(): response["is_day"] = True else: response["is_night"] = True if -6 <= city.solar_zenith() <= 0: response["is_civil_twlight"] = True response["is_day"] = False response["is_night"] = False elif -12 <= city.solar_zenith() <= -6: response["is_nautical_twlight"] = True response["is_day"] = False response["is_night"] = False elif -18 <= city.solar_zenith() <= -12: response["is_astronomical_twilight"] = True response["is_day"] = False response["is_night"] = False if -6 <= city.solar_zenith() <= -4: response["is_blue_hour"] = True elif -4 <= city.solar_zenith() <= 6: response["is_golden_hour"] = True if 0 <= city.moon_phase() < 7: response["moon_phase"] = "new-moon" elif 7 <= city.moon_phase() < 14: response["moon_phase"] = "first-quarter" elif 14 <= city.moon_phase() < 21: response["moon_phase"] = "full-moon" elif 21 <= city.moon_phase(): response["moon_phase"] = "last-quarter" return jsonify(response)
def sun(request): """ Return sunrise, sunset etc. times. """ a = Astral() a.solar_depression = 'civil' l = Location() # l.name = 'Lapinlahden sairaala' # l.region = 'Helsinki' lat = request.GET.get('lat') lon = request.GET.get('lon') if lat is None or lon is None: l.latitude = 60.167761 l.longitude = 24.9118141 l.loc_source = 'default' else: l.latitude = float(lat) l.longitude = float(lon) l.loc_source = 'request' l.timezone = 'UTC' l.elevation = 0 timeformat = request.GET.get('timeformat', 'epoch') date_str = request.GET.get('date') format_str = request.GET.get('format', 'json') date = datetime.datetime.now().date() if date_str is not None: date = parse(date_str).date() pass sundata = { 'now': datetime.datetime.now(tz=pytz.UTC), # .astimezone(pytz.UTC), 'date': date.strftime('%Y-%m-%d'), 'lat': l.latitude, 'lon': l.longitude, 'loc_source': l.loc_source, } try: sun = l.sun(date=date, local=False) except AstralError as e: return HttpResponse(json.dumps({'error': str(e)}), content_type='application/json') for k in ['dawn', 'sunrise', 'noon', 'sunset', 'dusk']: sundata[k] = sun[k] if timeformat == 'iso': for k in sundata.keys(): if isinstance(sundata[k], datetime.datetime): sundata[k] = sundata[k].isoformat() else: # timeformat == 'epoch': for k in sundata.keys(): if isinstance(sundata[k], datetime.datetime): sundata[k] = int(sundata[k].timestamp()) res_str = json.dumps(sundata, indent=2) return HttpResponse(res_str, content_type='application/json')
class plugin: ''' A class to display the time of sunrise/sunset Uses the astral library to retrieve information... ''' def __init__(self, config): ''' Initializations for the startup of the weather forecast ''' # Get plugin name (according to the folder, it is contained in) self.name = os.path.dirname(__file__).split('/')[-1] self.astral_at_location = Astral()[config.get('plugin_' + self.name, 'location')] # Choose language to display sunrise language = config.get('plugin_time_default', 'language') if language == 'german': self.taw = wcp_time_german.time_german() elif language == 'dutch': self.taw = wcp_time_dutch.time_dutch() else: print('Could not detect language: ' + language + '.') print('Choosing default: german') self.taw = wcp_time_german.time_german() self.bg_color_index = 0 # default background color: black self.word_color_index = 2 # default word color: warm white self.minute_color_index = 2 # default minute color: warm white def run(self, wcd, wci): ''' Displaying current time for sunrise/sunset ''' # Get data of sunrise sun_data = self.astral_at_location.sun(date=datetime.datetime.now(), local=True) # Display data of sunrise wcd.animate(self.name, 'sunrise', invert=True) wcd.setColorToAll(wcc.colors[self.bg_color_index], includeMinutes=True) taw_indices = self.taw.get_time(sun_data['sunrise'], withPrefix=False) wcd.setColorBy1DCoordinates(wcd.strip, taw_indices, wcc.colors[self.word_color_index]) wcd.show() time.sleep(3) # Display data of sunset wcd.animate(self.name, 'sunrise') wcd.setColorToAll(wcc.colors[self.bg_color_index], includeMinutes=True) taw_indices = self.taw.get_time(sun_data['sunset'], withPrefix=False) wcd.setColorBy1DCoordinates(wcd.strip, taw_indices, wcc.colors[self.word_color_index]) wcd.show() time.sleep(3) # Display current moon phase moon_phase = self.astral_at_location.moon_phase(datetime.datetime.now()) for i in range(0, moon_phase): wcd.showIcon('sunrise', 'moon_'+str(i).zfill(2)) time.sleep(0.1) time.sleep(3)
def test_Astral_Nighttime(): a = Astral() l = a['London'] d = datetime.date(2016, 1, 6) start, end = a.night_utc(d, l.latitude, l.longitude) cstart = datetime.datetime(2016, 1, 6, 18, 10, 0, tzinfo=pytz.UTC) cend = datetime.datetime(2016, 1, 7, 6, 2, 0, tzinfo=pytz.UTC) assert datetime_almost_equal(start, cstart, 300) assert datetime_almost_equal(end, cend, 300)
def update_sun_position(self, utc_point_in_time): """Calculate the position of the sun.""" from astral import Astral self.solar_azimuth = Astral().solar_azimuth(utc_point_in_time, self.location.latitude, self.location.longitude) self.solar_elevation = Astral().solar_elevation( utc_point_in_time, self.location.latitude, self.location.longitude)
def testElevation(): city_name = "Jubail" dd = Astral() city = dd[city_name] dt = datetime.datetime.now(tz=city.tz) print("Date & time: %s" % dt) print("Date & time (UTC): %s" % dt.astimezone(pytz.utc)) print("Elevation: %.02f" % dd.solar_elevation(dt, city.latitude, city.longitude))
def SetSunTimes(): cityName = "London" a = Astral() a.solar_depression = "civil" city = a[cityName] sun = city.sun(date=datetime.now(), local=True) variables.Set("dawn", str(sun['dawn'].strftime("%H:%M"))) variables.Set("sunrise", str(sun['sunrise'].strftime("%H:%M"))) variables.Set("sunset", str(sun['sunset'].strftime("%H:%M"))) variables.Set("dusk", str(sun['dusk'].strftime("%H:%M")))
def get_sun(): a = Astral() a.solar_depression = 'civil' city = a['Helsinki'] sun = city.sun(date=datetime.now(), local=True) sunset = sun['dusk'] sun = city.sun(date=datetime.now() + timedelta(days=1), local=True) sunrise = sun['dawn'] return sunrise, sunset
def sun_api(): data = {} city_name = 'Denver' a = Astral() a.solar_depression = 'civil' city = a[city_name] sun = city.sun(date=dt.datetime.today(), local=True) data = {k: sun[k].hour * 60 + sun[k].minute for k in sun} data['moon_phase'] = city.moon_phase() return data
def test_Astral_JulianDay_DateTime(): a = Astral() dt = datetime.datetime(2015, 1, 1, 1, 36, 0) jd = a._julianday(dt) assert float_almost_equal(jd, 2457023.57, 0.1) dt = datetime.datetime(2015, 1, 1, 15, 12, 0) jd = a._julianday(dt) assert float_almost_equal(jd, 2457024.13, 0.1)
def test_Astral_JulianDay_DateTimeZone(): a = Astral() dt = datetime.datetime(2015, 1, 1, 1, 36, 0) jd = a._julianday(dt, 1) assert float_almost_equal(jd, 2457023.51, 0.1) dt = datetime.datetime(2015, 10, 10, 1, 36, 0) jd = a._julianday(dt, 5) assert float_almost_equal(jd, 2457305.36, 0.1)
def its_after_sunset(city_name): a = Astral() a.solar_depression = 'civil' city = a[city_name] sun = city.sun(date=date.today(), local=True) sunset_today = (sun['sunset']).replace(tzinfo=None) if sunset_today < datetime.today(): return True else: return False
class plugin: """ A class to display the time of sunrise/sunset Uses the astral library to retrieve information... """ def __init__(self, config): """ Initializations for the startup of the weather forecast """ # Get plugin name (according to the folder, it is contained in) self.name = os.path.dirname(__file__).split('/')[-1] self.pretty_name = "Sunrise" self.description = "Displays the current times of sunrise and sunset." self.astral_at_location = Astral()[config.get('plugin_' + self.name, 'location')] self.bg_color_index = 0 # default background color: black self.word_color_index = 2 # default word color: warm white self.minute_color_index = 2 # default minute color: warm white def run(self, wcd, wci): """ Displaying current time for sunrise/sunset """ # Get data of sunrise sun_data = self.astral_at_location.sun(date=datetime.datetime.now(), local=True) # Display data of sunrise wcd.animate(self.name, 'sunrise', invert=True) wcd.setColorToAll(wcc.colors[self.bg_color_index], includeMinutes=True) taw_indices = wcd.taw.get_time(sun_data['sunrise'], purist=True) wcd.setColorBy1DCoordinates(taw_indices, wcc.colors[self.word_color_index]) wcd.show() if wci.waitForExit(3.0): return # Display data of sunset wcd.animate(self.name, 'sunrise') wcd.setColorToAll(wcc.colors[self.bg_color_index], includeMinutes=True) taw_indices = wcd.taw.get_time(sun_data['sunset'], purist=True) wcd.setColorBy1DCoordinates(taw_indices, wcc.colors[self.word_color_index]) wcd.show() if wci.waitForExit(3.0): return # Display current moon phase moon_phase = int( self.astral_at_location.moon_phase(datetime.datetime.now())) for i in range(0, moon_phase): wcd.showIcon('sunrise', 'moon_' + str(i).zfill(2)) if wci.waitForExit(0.1): return if wci.waitForExit(3.0): return
def test_track_sunrise(self): """Test track the sunrise.""" latitude = 32.87336 longitude = 117.22743 # Setup sun component self.hass.config.latitude = latitude self.hass.config.longitude = longitude setup_component(self.hass, sun.DOMAIN, { sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) # Get next sunrise/sunset astral = Astral() utc_now = dt_util.utcnow() mod = -1 while True: next_rising = (astral.sunrise_utc(utc_now + timedelta(days=mod), latitude, longitude)) if next_rising > utc_now: break mod += 1 # Track sunrise runs = [] unsub = track_sunrise(self.hass, lambda: runs.append(1)) offset_runs = [] offset = timedelta(minutes=30) unsub2 = track_sunrise(self.hass, lambda: offset_runs.append(1), offset) # run tests self._send_time_changed(next_rising - offset) self.hass.block_till_done() self.assertEqual(0, len(runs)) self.assertEqual(0, len(offset_runs)) self._send_time_changed(next_rising) self.hass.block_till_done() self.assertEqual(1, len(runs)) self.assertEqual(0, len(offset_runs)) self._send_time_changed(next_rising + offset) self.hass.block_till_done() self.assertEqual(2, len(runs)) self.assertEqual(1, len(offset_runs)) unsub() unsub2() self._send_time_changed(next_rising + offset) self.hass.block_till_done() self.assertEqual(2, len(runs)) self.assertEqual(1, len(offset_runs))
def testAzimuth(): city_name = "Jubail" dd = Astral() city = dd[city_name] print("Latitude: %f, Longitude: %f" % (city.latitude, city.longitude)) dt = datetime.datetime.now(tz=city.tz) print("Date & time: %s" % dt) print("Date & time (UTC): %s" % dt.astimezone(pytz.utc)) print("Azimuth: %.02f" % dd.solar_azimuth(dt, city.latitude, city.longitude))
def its_between_dawn_sunset(city_name): a = Astral() a.solar_depression = 'civil' city = a[city_name] sun = city.sun(date=date.today(), local=True) dawn_today = (sun['dawn']).replace(tzinfo=None) sunset_today = (sun['sunset']).replace(tzinfo=None) if (dawn_today < datetime.today()) and (sunset_today > datetime.today()): return True else: return False
def initAstral(self): a = Astral() a.solar_depression = 'civil' l = Location() l.name = 'Dolbeau-Mistassini' l.region = 'Canada' l.latitude = 48.9016 l.longitude = -72.2156 l.timezone = 'America/Montreal' l.elevation = 139 self.location = l
def its_light_in(city_name): a = Astral() a.solar_depression = 'civil' city = a[city_name] sun = city.sun(date=date.today(), local=True) dawn_today = (sun['dawn']).replace(tzinfo=None) if dawn_today < datetime.today(): return True else: return False
def setup_location(): global city city_name = 'Bucharest' a = Astral() a.solar_depression = 'civil' city = a[city_name] print('Solar data for %s/%s\n' % (city_name, city.region)) timezone = city.timezone print('Timezone: %s' % timezone)
def SunUpDown(location): a = Astral() a.solar_depression = 'civil' timezone = location.timezone Now = strftime("%H:%M", localtime()) dt = datetime.datetime.fromtimestamp(time.mktime(localtime())) tz = pytz.timezone("Europe/Berlin") dtn = tz.localize(dt) dtnT = dtn + datetime.timedelta(days=1) sun = location.sun(dtn, local=True) sunT = location.sun(dtnT, local=True) if (sun['sunrise'].hour < 10): Sunrise = '0' + str(sun['sunrise'].hour) + ':' else: Sunrise = str(sun['sunrise'].hour) + ':' if (sun['sunrise'].minute < 10): Sunrise = Sunrise + '0' + str(sun['sunrise'].minute) else: Sunrise = Sunrise + str(sun['sunrise'].minute) if (sunT['sunrise'].hour < 10): SunriseT = '0' + str(sunT['sunrise'].hour) + ':' else: SunriseT = str(sunT['sunrise'].hour) + ':' if (sunT['sunrise'].minute < 10): SunriseT = SunriseT + '0' + str(sunT['sunrise'].minute) else: SunriseT = SunriseT + str(sunT['sunrise'].minute) if (sun['sunset'].hour < 10): Sunset = '0' + str(sun['sunset'].hour) + ':' else: Sunset = str(sun['sunset'].hour) + ':' if (sun['sunset'].minute < 10): Sunset = Sunset + '0' + str(sun['sunset'].minute) else: Sunset = Sunset + str(sun['sunset'].minute) if (sunT['sunset'].hour < 10): SunsetT = '0' + str(sunT['sunset'].hour) + ':' else: SunsetT = str(sunT['sunset'].hour) + ':' if (sunT['sunset'].minute < 10): SunsetT = SunsetT + '0' + str(sunT['sunset'].minute) else: SunsetT = SunsetT + str(sunT['sunset'].minute) ''' print sun['sunrise'], sun['sunset'] print print sunT['sunrise'], sunT['sunset'] print '-------------' ''' return Sunrise, Sunset, SunriseT, SunsetT, sun['sunrise'], sun['sunset'], ( (dtn > sun['sunrise']) and (dtn < sun['sunset']))
def sunyears(start_year, end_year): city_name = 'London' a = Astral() a.solar_depression = 'civil' city = a[city_name] sun_times = {} print('Information for %s/%s\n' % (city_name, city.region)) timezone = city.timezone print('Timezone: %s' % timezone) print(' Latitude: %.02f; Longitude: %.02f\n' % (city.latitude, city.longitude)) delta = datetime.timedelta(days=1) for year in range(start_year, end_year + 1): # Loop through all days in year start_date = datetime.date(year, 1, 1) end_date = datetime.date(year, 12, 31) d = start_date while d <= end_date: sun = city.sun(d, local=True) # print('Dawn: %s' % str(sun['dawn'])) # print('Sunrise: %s' % str(sun['sunrise'])) # print('Noon: %s' % str(sun['noon'])) # print('Sunset: %s' % str(sun['sunset'])) # print('Dusk: %s' % str(sun['dusk'])) # pprint(sun) sun_times[json_serial(d)] = sun # print(json.dumps(sun_times, default=json_serial, # indent=4, sort_keys=True)) d += delta # print(json.dumps(sun_times, default=json_serial)) outfilename = "suntimes-{}-{}".format(start_year, end_year) outfilename = os.path.join("data", outfilename) mkdir("data") with open(outfilename + ".json", "w") as outfile: json.dump(sun_times, outfile, default=json_serial, indent=4, separators=(',', ': '), sort_keys=True) with open(outfilename + ".min.json", "w") as outfile: json.dump(sun_times, outfile, default=json_serial)
def main(): a = Astral() a.solar_depression = 'civil' city = a['Birmingham'] timezone = city.timezone sun = city.sun(date=datetime.date.today(), local=True) if is_light_outside(sun['dawn'], sun['dusk']): logger.info("Its light outside, switching off...") switch_off() else: logger.info("Its dark outside, switching on...") switch_on()
def daytime(): """ Compute whether it is currently daytime based on current location """ city = Astral()[CITY] sundata = city.sun() sunrise = sundata['sunrise'] + timedelta(minutes=DELTA) sunset = sundata['sunset'] - timedelta(minutes=DELTA) now = datetime.now(sunrise.tzinfo) return sunrise < now < sunset
def get_phase_segment(): a = Astral() moon_phase = a.moon_phase(datetime.datetime.now()) if 0 < moon_phase < 4: return new_moon_icon if 4 < moon_phase < 10: return first_quarter_icon if 10 < moon_phase < 17: return full_moon_icon if 17 < moon_phase < 26: return last_quarter_icon if 26 < moon_phase < 29: return new_moon_icon
class plugin: """ A class to display the time of sunrise/sunset Uses the astral library to retrieve information... """ def __init__(self, config): """ Initializations for the startup of the weather forecast """ # Get plugin name (according to the folder, it is contained in) self.name = os.path.dirname(__file__).split('/')[-1] self.pretty_name = "Sunrise" self.description = "Displays the current times of sunrise and sunset." self.astral_at_location = Astral()[config.get('plugin_' + self.name, 'location')] self.bg_color_index = 0 # default background color: black self.word_color_index = 2 # default word color: warm white self.minute_color_index = 2 # default minute color: warm white def run(self, wcd, wci): """ Displaying current time for sunrise/sunset """ # Get data of sunrise sun_data = self.astral_at_location.sun(date=datetime.datetime.now(), local=True) # Display data of sunrise wcd.animate(self.name, 'sunrise', invert=True) wcd.setColorToAll(wcc.colors[self.bg_color_index], includeMinutes=True) taw_indices = wcd.taw.get_time(sun_data['sunrise'], purist=True) wcd.setColorBy1DCoordinates(wcd.strip, taw_indices, wcc.colors[self.word_color_index]) wcd.show() if wci.waitForExit(3.0): return # Display data of sunset wcd.animate(self.name, 'sunrise') wcd.setColorToAll(wcc.colors[self.bg_color_index], includeMinutes=True) taw_indices = wcd.taw.get_time(sun_data['sunset'], purist=True) wcd.setColorBy1DCoordinates(wcd.strip, taw_indices, wcc.colors[self.word_color_index]) wcd.show() if wci.waitForExit(3.0): return # Display current moon phase moon_phase = int(self.astral_at_location.moon_phase(datetime.datetime.now())) for i in range(0, moon_phase): wcd.showIcon('sunrise', 'moon_' + str(i).zfill(2)) if wci.waitForExit(0.1): return if wci.waitForExit(3.0): return
def sunyears(start_year, end_year): city_name = 'London' a = Astral() a.solar_depression = 'civil' city = a[city_name] sun_times = {} print('Information for %s/%s\n' % (city_name, city.region)) timezone = city.timezone print('Timezone: %s' % timezone) print(' Latitude: %.02f; Longitude: %.02f\n' % (city.latitude, city.longitude)) delta = datetime.timedelta(days=1) for year in range(start_year, end_year+1): # Loop through all days in year start_date = datetime.date(year, 1, 1) end_date = datetime.date(year, 12, 31) d = start_date while d <= end_date: sun = city.sun(d, local=True) # print('Dawn: %s' % str(sun['dawn'])) # print('Sunrise: %s' % str(sun['sunrise'])) # print('Noon: %s' % str(sun['noon'])) # print('Sunset: %s' % str(sun['sunset'])) # print('Dusk: %s' % str(sun['dusk'])) # pprint(sun) sun_times[json_serial(d)] = sun # print(json.dumps(sun_times, default=json_serial, # indent=4, sort_keys=True)) d += delta # print(json.dumps(sun_times, default=json_serial)) outfilename = "suntimes-{}-{}".format(start_year, end_year) outfilename = os.path.join("data", outfilename) mkdir("data") with open(outfilename + ".json", "w") as outfile: json.dump(sun_times, outfile, default=json_serial, indent=4, separators=(',', ': '), sort_keys=True) with open(outfilename + ".min.json", "w") as outfile: json.dump(sun_times, outfile, default=json_serial)
def plot_nightshade(df, ax, **kwargs): a = Astral() a.solar_depression = 'civil' city = a['wellington'] ymin, ymax = ax.get_ylim() for day in pd.date_range(df.index[0].date(), df.index[-1].date()): sun1 = city.sun(date=day - dt.timedelta(days=1)) sun2 = city.sun(date=day, local=True) sunset = sun1['sunset'].replace(tzinfo=None) sunrise = sun2['sunrise'].replace(tzinfo=None) night = pd.DataFrame(index=[sunset, sunrise], data=dict(shade=[ymax, ymax])) night.shade.plot(kind='area', ax=ax, color='0.9', alpha=0.5, **kwargs)
def __init__(self, config): ''' Initializations for the startup of the weather forecast ''' # Get plugin name (according to the folder, it is contained in) self.name = os.path.dirname(__file__).split('/')[-1] self.astral_at_location = Astral()[config.get('plugin_' + self.name, 'location')] # Choose language to display sunrise language = config.get('plugin_time_default', 'language') if language == 'german': self.taw = wcp_time_german.time_german() elif language == 'dutch': self.taw = wcp_time_dutch.time_dutch() elif language == 'swiss_german': self.taw = wcp_swiss_german.time_swiss_german() else: print('Could not detect language: ' + language + '.') print('Choosing default: german') self.taw = wcp_time_german.time_german() self.bg_color_index = 0 # default background color: black self.word_color_index = 2 # default word color: warm white self.minute_color_index = 2 # default minute color: warm white
def test_track_sunset(self): """Test track sunset decorator.""" latitude = 32.87336 longitude = 117.22743 # Setup sun component self.hass.config.latitude = latitude self.hass.config.longitude = longitude sun.setup(self.hass, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) # Get next sunrise/sunset astral = Astral() utc_now = dt_util.utcnow() mod = -1 while True: next_setting = (astral.sunset_utc(utc_now + timedelta(days=mod), latitude, longitude)) if next_setting > utc_now: break mod += 1 # Use decorator runs = [] decor = track_sunset() decor(lambda x: runs.append(1)) offset_runs = [] offset = timedelta(minutes=30) decor = track_sunset(offset) decor(lambda x: offset_runs.append(1)) # run tests self._send_time_changed(next_setting - offset) self.hass.pool.block_till_done() self.assertEqual(0, len(runs)) self.assertEqual(0, len(offset_runs)) self._send_time_changed(next_setting) self.hass.pool.block_till_done() self.assertEqual(1, len(runs)) self.assertEqual(0, len(offset_runs)) self._send_time_changed(next_setting + offset) self.hass.pool.block_till_done() self.assertEqual(2, len(runs)) self.assertEqual(1, len(offset_runs))
def test_date_events(self): """Test retrieving next sun events.""" utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC) from astral import Astral astral = Astral() utc_today = utc_now.date() latitude = self.hass.config.latitude longitude = self.hass.config.longitude dawn = astral.dawn_utc(utc_today, latitude, longitude) dusk = astral.dusk_utc(utc_today, latitude, longitude) midnight = astral.solar_midnight_utc(utc_today, longitude) noon = astral.solar_noon_utc(utc_today, longitude) sunrise = astral.sunrise_utc(utc_today, latitude, longitude) sunset = astral.sunset_utc(utc_today, latitude, longitude) self.assertEqual(dawn, sun.get_astral_event_date( self.hass, 'dawn', utc_today)) self.assertEqual(dusk, sun.get_astral_event_date( self.hass, 'dusk', utc_today)) self.assertEqual(midnight, sun.get_astral_event_date( self.hass, 'solar_midnight', utc_today)) self.assertEqual(noon, sun.get_astral_event_date( self.hass, 'solar_noon', utc_today)) self.assertEqual(sunrise, sun.get_astral_event_date( self.hass, 'sunrise', utc_today)) self.assertEqual(sunset, sun.get_astral_event_date( self.hass, 'sunset', utc_today))
def test_date_events(self): """Test retrieving next sun events.""" utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC) from astral import Astral astral = Astral() utc_today = utc_now.date() latitude = self.hass.config.latitude longitude = self.hass.config.longitude dawn = astral.dawn_utc(utc_today, latitude, longitude) dusk = astral.dusk_utc(utc_today, latitude, longitude) midnight = astral.solar_midnight_utc(utc_today, longitude) noon = astral.solar_noon_utc(utc_today, longitude) sunrise = astral.sunrise_utc(utc_today, latitude, longitude) sunset = astral.sunset_utc(utc_today, latitude, longitude) assert dawn == sun.get_astral_event_date( self.hass, 'dawn', utc_today) assert dusk == sun.get_astral_event_date( self.hass, 'dusk', utc_today) assert midnight == sun.get_astral_event_date( self.hass, 'solar_midnight', utc_today) assert noon == sun.get_astral_event_date( self.hass, 'solar_noon', utc_today) assert sunrise == sun.get_astral_event_date( self.hass, SUN_EVENT_SUNRISE, utc_today) assert sunset == sun.get_astral_event_date( self.hass, SUN_EVENT_SUNSET, utc_today)
def getRainLevel(self): if self.Weather == None: return "norain" city_name = 'London' a = Astral() a.solar_depression = 'civil' city = a[city_name] now = datetime.datetime.utcnow().replace(tzinfo=utc) sun = city.sun(date=datetime.datetime.now(), local=True) if now < sun['dawn']: #night weatherNum = self.Weather.getWeatherTypeNum(0, 1) elif now < sun['sunrise']: #sunrise weatherNum = self.Weather.getWeatherTypeNum() elif now < sun['sunset']: #day weatherNum = self.Weather.getWeatherTypeNum() elif now < sun['dusk']: #sunset weatherNum = self.Weather.getWeatherTypeNum(0, 1) else: #night weatherNum = self.Weather.getWeatherTypeNum(0, 1) if 0 <= int(weatherNum) <= 8: return "norain" elif 9 <= int(weatherNum) <= 10: return "lightrain" elif int(weatherNum) == 11: return "drizzel" elif int(weatherNum) == 12: return "lightrain" elif 13 <= int(weatherNum) <= 15: return "heavyrain" elif 16 <= int(weatherNum) <= 27: return "norain" elif 28 <= int(weatherNum) <= 29: return "heavyrain" else: return "norain"
def brightness(city, at=None) -> str: """ :param city: str e.g. "Amsterdam" :param at: datetime :return: str one of the values "night, dawn, day, dusk" depending on the time """ if at is None: at = datetime.datetime.now() astral = Astral() astral.solar_depression = 'nautical' location = astral[city] sun = location.sun(date=at) at = pytz.timezone(location.timezone).localize(at) dawn = sun['dawn'] sunrise = sun['sunrise'] sunset = sun['sunset'] dusk = sun['dusk'] if at >= dawn and at < sunrise: return DAWN if at >= sunrise and at < sunset: return DAY if at >= sunset and at < dusk: return DUSK return NIGHT