class Weather: def __init__(self): self.owm = OWM('4526d487f12ef78b82b7a7d113faea64') self.mgr = self.owm.weather_manager() self.city_counter = 1 self.cities = { 1 : 'krakow', 2 : 'london', 3 : 'stockholm' } def update_city_counter(self): self.city_counter += 1 if self.city_counter == 4: self.city_counter = 1 def get_weather(self, city): observation = self.mgr.weather_at_place(city) weather = observation.weather result = { 'status' : weather.status, 'temp' : weather.temperature('celsius').get('temp') } return result def get_next_weather(self): self.update_city_counter() return self.get_weather(self.cities[self.city_counter])
def main(owm_api_key, ifttt_api_key, temp_threshold, high_temp_event_name, normal_temp_event_name, city, force_high): """ If *either* the outside temperature is over a threshold, *or* some other temperature (currently motherboard temp, measured outside this script) is over a threshold, consider the temperature "high". Send an event to IFTTT so we can take action (like turning on a fan). """ owm = OWM(owm_api_key) weather_manager = owm.weather_manager() observation = weather_manager.weather_at_place(city) temp = observation.weather.temperature('celsius')['temp'] event_name = normal_temp_event_name if temp > temp_threshold or force_high: event_name = high_temp_event_name previous_event = get_last_event() if previous_event != event_name: ifttt_url = 'https://maker.ifttt.com/trigger/%s/with/key/%s' % (event_name, ifttt_api_key) ifttt_data = {'value1': temp, 'value2': 'forced: %s' % force_high} requests.post(ifttt_url, data=ifttt_data) write_event(event_name, ifttt_data)
def get_weather(): key = '8f1b9a3225495a9c8a89cb7ff7848c08' owm = OWM(key) mgr = owm.weather_manager() observation = mgr.weather_at_place('Risod, IN') weather = observation.weather return f"The weather status is {weather.status}"
def main(strip): print(f"Good morning! Waking up at {time.time()}") owm = OWM(WEATHER_API_KEY) mgr = owm.weather_manager() observation = mgr.weather_at_place( "Oxford,GB" ) # the observation object is a box containing a weather object weather = observation.weather.status print(f"The current weather is {weather}") start_time = time.time() strip.begin() dither_fade(strip, ws.Color(0, 1, 1), leds_to_switch=None, dither_time=RUNTIME * 0.5) WEATHER_ANIMATIONS[weather](strip, RUNTIME) time.sleep(10 * 60) WEATHER_ANIMATIONS[weather](strip, RUNTIME, reverse=True) dither_fade(strip, ws.Color(0, 0, 0), leds_to_switch=None, dither_time=RUNTIME * 0.5) end_time = time.time() print( f"I hope you're awake! Closing down at {time.time()}. We spent {(end_time - start_time) // 60} minutes." )
def get_data(key, city): """ Получение данных на сегодняшний день. key - ключ от openweathermap.org city - город с уточнением страны """ get_err = False try: config_dict = get_default_config() config_dict['language'] = 'ru' owm = OWM(api_key=key, config=config_dict) mgr = owm.weather_manager() w = mgr.weather_at_place(city).weather except: get_err = "Сведения о погоде получить не удалось." data = ("%s. " "Сегодня %s, %s. " "Время %s. " % (get_greeting(), get_weekday(), get_date(), get_time())) if not get_err: data += ("Температура за окном %d ℃. " "Ветер %s, %d м в секунду. " "Атмосферное давление %d мм рт. ст. " "Относительная влажность воздуха %d %%. " "%s." % (w.temperature('celsius').get('temp'), get_wind_direction(w.wind().get('deg')), w.wind().get('speed'), w.pressure.get('press') * 0.75006375541921, w.humidity, w.detailed_status)) else: data += get_err return data
def get_weather(self): owm = OWM(self.api_key) weather_mgr = owm.weather_manager() city_id_registry = owm.city_id_registry() london = city_id_registry.ids_for('London', 'GB')[0][0] weather = weather_mgr.weather_at_id(london).weather temperature = weather.temperature('celsius') forecast = weather_mgr.forecast_at_id(london, '3h', 4).forecast forecasts = [] for hourly_forecast in forecast: forecasts.append( ForecastInfo( hourly_forecast.reference_time('date'), hourly_forecast.detailed_status, round(hourly_forecast.temperature('celsius')['temp'], 1), hourly_forecast.weather_code)) current_weather = WeatherInfo(london, weather.reference_time('date'), weather.detailed_status, round(temperature['temp'], 1), round(temperature['temp_max'], 1), round(temperature['temp_min'], 1), weather.sunrise_time('date'), weather.sunset_time('date'), weather.weather_code, forecasts) return current_weather
def lambda_handler(event, context): #TODO implement logger.debug(event) city = event["currentIntent"]["slots"]["City"] owm = OWM('068b6ba70ba098c7ef600f077f63ce08') #API key mngr = owm.weather_manager() weather = mngr.weather_at_place(city).weather temp_dict_celsius = weather.temperature('celsius') sunrise_date = weather.sunrise_time(timeformat='date') sunrset_date = weather.sunset_time(timeformat='date') answer = "The weather of " + city + " is " + weather.detailed_status + " with " + str( temp_dict_celsius['temp'] ) + " C as average temperature. The sun rose at around " + str( sunrise_date) + " and is expected to set at around " + str( sunrset_date) return { "sessionAttributes": event["sessionAttributes"], "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": answer } } }
def send_info(message): config_dict = get_default_config() config_dict['language'] = 'ua' # your language here, eg. Ukrainian owm = OWM('KEY', config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(message.text) w = observation.weather # Temp temp = w.temperature('celsius') temp_current = temp['temp'] temp_min = temp['temp_min'] temp_max = temp['temp_max'] feels_like = temp['feels_like'] # Wind wind_info = observation.weather.wind(unit='meters_sec') wind_speed = wind_info['speed'] wind_deg = wind_info['deg'] bot.reply_to( message, 'Температура зараз: ' + str(temp_current) + '\n \nМінімальна температура сьогодні: ' + str(temp_min) + ' градуси' '\n \nМаксимальна температура сьогодні: ' + str(temp_max) + ' градуси' + '\n \nВідчувається як: ' + str(feels_like) + ' градуси' + '\n \nШвидкість вітру' + 'сьогодні: ' + str(wind_speed) + ' метра за секунду' + '\n \n Напрям вітру у градусах від ' + 'північного ' + 'горизонту: ' + str(wind_deg))
def get_forecast(self): """Assembles an OpenWeatherMap API call using pyowm, gets the forecast temperature for the next eight hours.""" # Builds pyowm call to the OWM API for a location's hourly temps load_dotenv('owm_config.env') api_key = getenv('API_KEY') lat = float(getenv('LATITUDE')) lon = float(getenv('LONGITUDE')) print(f"{lat}, {lon}") owm = OWM(api_key) mgr = owm.weather_manager() one_call = mgr.one_call(lat=lat, lon=lon, exclude='minutely,daily', units='imperial') for hour in self.forecast_temps: self.forecast_temps[hour] = one_call.forecast_hourly[ hour].temperature().get('temp') print(self.forecast_temps) # Logs the forecast temps to a .csv file now = datetime.now().isoformat(' ') log_timestamp = {'Timestamp': now} coords = {'Lat': lat, 'Lon': lon} row_dict = {**log_timestamp, **coords, **self.forecast_temps} field_names = row_dict.keys() file_exists = path.exists('Forecast Log.csv') with open('Forecast Log.csv', 'a+', newline='') as forecast_log: dict_writer = DictWriter(forecast_log, fieldnames=field_names) if not file_exists: dict_writer.writeheader() dict_writer.writerow(row_dict)
def main(say, widget): for i in trigger: if i == say: id = OWM('e45bc007f87a48d597d60091779f2d88', config_dict) # API ключ Open weather map mgr = id.weather_manager() try: city = location.geo.city observation = mgr.weather_at_place(city) w = observation.weather toSpeak = "В " + city + " сейчас " + str(int(w.temperature('celsius')['temp'])) +\ " градусов по цельсию, " + w.detailed_status + "." if float(w.temperature('celsius')['temp']) >= 20: toSpeak += "\nСейчас на улице жарко. Идите загорать." elif float(w.temperature('celsius')['temp']) <= 19 and float( w.temperature('celsius')['temp']) >= 10: toSpeak += "\nЗа окном прохладно. Оденьте куртку." elif float(w.temperature('celsius')['temp']) <= 9 and float( w.temperature('celsius')['temp']) >= 0: toSpeak += "\nНа улице холодно. Оденьтесь в осеннюю одежду." else: toSpeak += "\nНа улице очень холодно, лучше туда не ходить. Выпейте горячего чаю." except Exception: toSpeak = "Пожалуйста, укажите название города!" break else: toSpeak = "" if toSpeak != "": speak.speak(toSpeak, widget) return toSpeak
def run(self, wcd, wci): """ Displaying expected temperature """ # Get current forecast if self.weather_service == 'yahoo': current_weather_forecast = pywapi.get_weather_from_yahoo( self.location_id) elif self.weather_service == 'weather_dot_com': current_weather_forecast = pywapi.get_weather_from_weather_com( self.location_id) elif self.weather_service == 'openweathermap': owm = OWM(self.owm_key) owm.config['language'] = 'de' mgr = owm.weather_manager() observation = mgr.weather_at_place(self.location_id) w = observation.weather current_weather_forecast = [] print(w.temperature('Celsius')) current_weather_forecast['current_conditions'][ 'temperature'] = w.temperature('Celsius')['temp'] # current_weather_forecast['current_conditions']['temp_max'] = w.temperature('Celsius')['temp_max'] # current_weather_forecast['current_conditions']['temp_min'] = w.temperature('Celsius')['temp_min'] else: print('Warning: No valid weather_forecast found!') return outdoor_temp = current_weather_forecast['current_conditions'][ 'temperature'] if self.temp_sensor_registered: try: sensor = Adafruit_DHT.AM2302 pin = self.pin_temp_sensor #indoor_temp = str(int(round(am2302_ths.get_temperature(self.pin_temp_sensor)))) humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) indoor_temp = str(int(round(temperature))) wcd.showText(outdoor_temp + '*', count=1, fps=8) wcd.showText(indoor_temp + '*', count=1, fg_color=wcc.GREEN, fps=8) wcd.showText(outdoor_temp + '*', count=1, fps=8) wcd.showText(indoor_temp + '*', count=1, fg_color=wcc.GREEN, fps=8) except: print(' Failed to read temperature sensor!') wcd.showText(outdoor_temp + '* ' + outdoor_temp + '* ' + outdoor_temp + '*', count=1, fps=8) else: wcd.showText(outdoor_temp + '* ' + outdoor_temp + '* ' + outdoor_temp + '*', count=1, fps=8) if wci.waitForExit(1.0): return
def get_temperature(): owm = OWM('8f1b9a3225495a9c8a89cb7ff7848c08') mgr = owm.weather_manager() weather = mgr.weather_at_place('Risod,IN').weather temp_dict_kelvin = weather.temperature() temp = temp_dict_kelvin['temp'] - 273.15 degree_sign = u'\N{DEGREE SIGN}' return f'The current temperature is {ceil(temp)}{degree_sign}C'
def weather(): #hava durumlarını api üzerinden çekip anlık olarak söyleyen method owm = OWM('bbe1108552e97a288646c8be7b776acf') weather_mngr = owm.weather_manager() observation = weather_mngr.weather_at_place('Izmir,TR') weather = observation.weather temperature = weather.temperature("celsius") speak("Sıcaklık " + str(temperature["temp"]) + "derece") speak("Hissedilen sıcaklık "+ str(temperature["feels_like"]) + "derece") speak("Hava durumu " + str(weather.detailed_status))
def get_speed(): from pyowm.owm import OWM owm = OWM('8f1b9a3225495a9c8a89cb7ff7848c08') mgr = owm.weather_manager() observation = mgr.weather_at_place('New Delhi,IN') wind_dict_in_meters_per_sec = observation.weather.wind() # Default unit: 'meters_sec' speed = wind_dict_in_meters_per_sec['speed'] speed = float(speed) return speed
def getWeather(): """ Gets current weather from OWN data, i.e "Clouds" """ owm = OWM("TOKEN HERE") mgr = owm.weather_manager() observation = mgr.weather_at_place('Bergen,NO') weather = observation.weather return weather.status
def get_openweathermap(): owm_config = None owm = None try: with open('/etc/sensors/openweathermap.json', 'r') as f: owm_config = json.loads(f.read()) owm = OWM(owm_config['key']) f.close() except Exception as ex: print('OpenWeatherMap API setup error: {ex}'.format(ex=ex)) return None if owm: weather = owm.weather_manager().weather_at_place( owm_config['place']).weather temp = weather.temperature('celsius') wind = weather.wind() wind_gust = 0 if 'gust' in wind.keys(): wind_gust = wind['gust'] precip_type = 'none' precip_intensity = 0 if weather.rain: precip_type = 'rain' precip_intensity = weather.rain['1h'] elif weather.snow: precip_type = 'snow' precip_intensity = weather.snow['1h'] return { 'sensor': owm_config['id'], 'ts': weather.reference_time(timeformat="unix"), 'dt': weather.reference_time(timeformat="date").astimezone(), 'units': 'si', 'summary': weather.detailed_status, 'icon': weather.weather_icon_name, 'weather_code': weather.weather_code, 'temp_c': temp['temp'], 'humidity': weather.humidity, 'pressure': weather.pressure['press'], 'dewpoint': magnus_dp(temp['temp'], weather.humidity), 'feels_like_c': temp['feels_like'], 'precip_type': precip_type, 'precip_intensity': precip_intensity, 'wind_speed': wind['speed'], 'wind_gust': wind_gust, 'wind_bearing': wind['deg'], 'cloud_cover': weather.clouds, 'uv_index': weather.uvi, 'visibility': weather.visibility_distance } return None
def getweather(city): owm = OWM(OWM_TOKEN, config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(city) w = observation.weather curr_weather = [int(w.temperature('celsius')['temp_min']), int(w.temperature('celsius')['temp_max']), int(w.temperature('celsius')['temp']), w.detailed_status] return curr_weather
class LocalWeather: """Class to hold the weather in user location. Arguments: ---------- key: Your API key for OpeWeather coords: A tuple for the lat. & lon. of your location """ def __init__(self, key, coords): self.key = key self.lat, self.lon = coords self.owm = OWM(self.key) self.mgr = self.owm.weather_manager() def _get_forecast(self): """Get forecast weather as list of tuples.""" # Access the One-Call API forecast one_call_forecast = self.mgr.one_call(self.lat, self.lon) hourly_weather = {(weather.reference_time('iso'), weather.pressure['press']) for weather in one_call_forecast.forecast_hourly} daily_weather = {(weather.reference_time('iso'), weather.pressure['press']) for weather in one_call_forecast.forecast_daily} return hourly_weather.union(daily_weather) def _get_history(self): """Get the historic weather.""" # Get the historic data is a 48hr interval starting 48hrs ago. two_day_epoch = int( (datetime.now() - timedelta(hours=48)).replace(tzinfo=timezone.utc).timestamp()) # Access the One-Call API history one_call_history = self.mgr.one_call_history(self.lat, self.lon, dt=two_day_epoch) hourly_weather = {(weather.reference_time('iso'), weather.pressure['press']) for weather in one_call_history.forecast_hourly} return hourly_weather def _combine_forecast_history(self): """Get and combine the forecast and history""" history = self._get_history() forecast = self._get_forecast() combined = list(history.union(forecast)) return [(dateutil.parser.isoparse(time), press) for time, press in combined] def plot_pressure(self): """Plot the pressure over time.""" combined_dataframe = pd.DataFrame(self._combine_forecast_history(), columns=['Time', 'Press']) combined_dataframe.set_index('Time').plot() plt.show()
def mess(message): get_message_bot = message.text.strip().lower() owm = OWM('4d9b5e79bfddd0b1bee5d376bbc02561') x = get_message_bot mgr = owm.weather_manager() observation = mgr.weather_at_place(x) w = observation.weather temp = w.temperature('celsius')['temp'] col = (f'Температура: {temp} , {w.status} ') bot.send_message(message.chat.id, col)
def get_weather(lat, long, config): api_key = config.get("owm", {}).get("key", "") if api_key == "": return ("", "Missing OWM API key", 0) owm = OWM(api_key) weather_manager = owm.weather_manager() observation = weather_manager.weather_at_coords(lat, long) w = observation.weather icon_name = w.weather_icon_name status = w.status temp = w.temperature("celsius")["temp"] return (icon_name, status, temp)
class CitySearch: def __init__(self): self.owm = OWM('246384c9beadbdc4eb18ced4c193e0ae') self.reg = self.owm.city_id_registry() self.mgr = self.owm.weather_manager() self.one_call = None def search_city(self, search_word): results = self.reg.ids_for(search_word) rv_dict = [{ 'text': str(name + ', ' + country) } for cityid, name, country in results] return rv_dict def get_weather_advice(self, city_details, hour_range): city_name = city_details[0] country_name = city_details[1] location = self.reg.locations_for(city_name, country=country_name) if isinstance(location, list): location = location[0] self.one_call = self.mgr.one_call(location.lat, location.lon) status_forecast = [ self.one_call.forecast_hourly[i].status for i in range(hour_range) ] rain_forecast = [ self.one_call.forecast_hourly[i].rain for i in range(hour_range) ] print(status_forecast) print(rain_forecast) advice = calculate_rain_chance(status_forecast, rain_forecast, hour_range) return advice def get_temperatures(self): temp_3h = [ self.one_call.forecast_hourly[i].temperature('celsius') for i in range(0, 13, 3) ] status_3h = [ self.one_call.forecast_hourly[i].status for i in range(0, 13, 3) ] icon_paths = [] for status in status_3h: if status == 'Clear': icon_paths.append('images\\sun.png') elif status == 'Clouds': icon_paths.append('images\\clouds.png') elif status == 'Rain': icon_paths.append('images\\rain.png') else: icon_paths.append('images\\snow.png') print(list(zip(icon_paths, temp_3h))) return list(zip(icon_paths, temp_3h))
def execute(self): city = self._match.group(1) config_dict = get_default_config() config_dict['language'] = 'en' owm = OWM('6d00d1d4e704068d70191bad2673e0cc', config_dict) reg = owm.city_id_registry() try: mgr = owm.weather_manager() observation = mgr.weather_at_place(city) #print(observation.location) w = re.findall('(\d+.\d+)', str(observation.location)) lon = float(w[1]) lat = float(w[2]) except: #проверка на частичное совпадение try: list_of_tuples = reg.ids_for(city, matching='like') city = list_of_tuples[0][1] except IndexError: print('No object with this name was found\n') return () #вывод списка с вариантами if len(list_of_tuples) > 1: for i in range(0, len(list_of_tuples)): print(i + 1, list_of_tuples[i][1:3]) #выбор пользователя и проверка try: select = int(input('\nSeveral matches were found. Enter a suitable number\n--> ')) city_finded = list_of_tuples[select - 1][1] list_of_locations = reg.locations_for(city_finded) city_finded = list_of_locations[0] lat = city_finded.lat lon = city_finded.lon if select < 1: print('Incorrected input\n') return () except: print('Incorrected input\n') return () print('Wait forecast for', city, '...\n') one_call = mgr.one_call(lat, lon) for i in range(3): print(datetime.now().date() + timedelta(days=1 + i)) print('Wind:', one_call.forecast_daily[i].wind().get('speed', 0), 'm/s\n' 'Cloudes:', one_call.forecast_daily[i].detailed_status, '\nDay temperature:', one_call.forecast_daily[i].temperature('celsius').get('feels_like_day', None), 'degrees Celsius', '\nNight temperature:', one_call.forecast_daily[i].temperature('celsius').get('feels_like_night', None), "degrees Celsius\n")
class WeatherService: def __init__(self, token): config_dict = config.get_default_config() config_dict['language'] = 'ru' self.__owm = OWM(api_key=token, config=config_dict) self.__weather_manager = self.__owm.weather_manager() def getCurrentWeather(self, city: str): weather = self.__weather_manager.weather_at_place(city) if weather is None: return city, None return weather.location.name, weather.weather
def weather(city_from_discord): """ Принимает на вход название города и выводит прогноз погоды """ config_dict = get_default_config() config_dict['language'] = 'ru' # your language here owm = OWM(OWM_API_KEY, config_dict) mgr = owm.weather_manager() observation = mgr.weather_at_place(city_from_discord) weather = observation.weather temperature = weather.temperature('celsius')['temp'] full_message = f'{weather.detailed_status.capitalize()}, температура в городе {city_from_discord} {round(temperature)}°C' return full_message
def main(): from time import sleep from gpiozero import AngularServo, Button owm = OWM('api_key') reg = owm.city_id_registry() mgr = owm.weather_manager() krakow = reg.ids_for('Kraków', country='PL')[0] istanbul = reg.ids_for('Istanbul', country='TR')[0] stockholm = reg.ids_for('Stockholm', country='SE')[0] global btn_state btn_state = 0 CITIES = [krakow, istanbul, stockholm] CITY_COUNT = 3 WEATHER = { 'clear': -70, 'mist': -30, 'haze': -30, 'smoke': 10, 'dust': 10, 'sand': 10, 'clouds': 10, 'ash': 10, 'squall': 10, 'drizzle': 50, 'rain': 50, 'snow': 50, 'thunderstorm': 50, 'tornado': 50 } servo1 = AngularServo(17, min_angle=-90, max_angle=90) servo1.angle = -90 def button1_pressed(): global btn_state btn_state += 1 print("Change to " + str(CITIES[btn_state % CITY_COUNT])) button1 = Button(11) button1.when_pressed = button1_pressed while True: weather = mgr.weather_at_id(CITIES[btn_state % CITY_COUNT][0]).weather status = str(weather.status).lower() servo1.angle = WEATHER.get(status) print(str(CITIES[btn_state % CITY_COUNT]) + " : " + status) sleep(3)
def get_weather(): f = open("key.txt", "r") api_key = f.read().replace("\n", "") # your API Key here as string owm = OWM(api_key) # Use API key to get data mgr = owm.weather_manager() # one_call = mgr.one_call(lat=47.36667, lon=8.55) observation = mgr.weather_at_place('Zurich') w = observation.weather temperature = w.temperature('celsius').get('temp', None) feels_temperature = w.temperature('celsius').get('feels_like', None) data = w.detailed_status # temperature = one_call.forecast_daily[0].temperature('celsius').get('day', None) # feels_temperature = one_call.forecast_daily[0].temperature('celsius').get('feels_like_day', None) # data = one_call.forecast_daily[0].detailed_status return temperature, feels_temperature, data
def __init__(self, api_key: str, city: str, country_code: str): """ Will create a OWM object daily forecaster object Arguments: :param api_key: the OpenWeatherMap api key :param city: the city where to get the prediction for, use https://openweathermap.org/find to locate yours :param country_code: the 2 capital letters country code where the city is located at if not set """ owm = OWM(api_key) self.mgr = owm.weather_manager() self.three_hour_forecast = self.mgr.forecast_at_place( city + "," + country_code, '3h')
def getWeather(df_resampled, inplace=True): if not (inplace): df_resampled = pd.DataFrame(df_resampled) solar_panel_sunrise = df_resampled.index[0].timestamp() solar_panel_sunset = df_resampled.index[-1].timestamp() # Retrieve current weather information (Requires the installation of pyowm. $ pip install pyowm) owm = OWM(OPENWEATHER) # a Python wrapper around the OpenWeatherMap API mgr = owm.weather_manager( ) # See: https://pyowm.readthedocs.io/en/latest/v3/code-recipes.html weather = mgr.one_call_history(lat=LAT, lon=LON, dt=round(solar_panel_sunrise)) #weather.forecast_daily # not sure why this is empty, bug? df_resampled['Temperature [C]'] = 0 # initialize all rows df_resampled['Status'] = '' # initialize all rows df_resampled['Detailed status'] = '' # initialize all rows df_resampled['Cloud cover [%]'] = 0 # initialize all rows df_resampled['Wind speed [m/s]'] = 0 # initialize all rows df_resampled['Wind angle [deg]'] = 0 # initialize all rows for forecast in weather.forecast_hourly: f_time = forecast.reference_time() f_time_str = datetime.utcfromtimestamp(f_time).strftime('%H:%M') ix = df_resampled.index.strftime( '%H:%M') == f_time_str # find corresponding row if any(ix): df_resampled.loc[ix, 'Temperature [C]'] = forecast.temperature( unit='celsius').get('temp', 0) df_resampled.loc[ix, 'Status'] = forecast.status # e.g. rain df_resampled.loc[ ix, 'Detailed status'] = forecast.detailed_status # e.g. light rain df_resampled.loc[ix, 'Cloud cover [%]'] = forecast.clouds wind = forecast.wind() df_resampled.loc[ix, 'Wind speed [m/s]'] = wind['speed'] df_resampled.loc[ix, 'Wind angle [deg]'] = wind['deg'] #forecast.sunrise_time() # seems to be None, at least in June #forecast.sunset_time() # seems to be None, at least in June else: logger.debug('ignoring weather at %s' % f_time_str) return df_resampled
def weather_now(self): """Grabs the weather for the location, assuming that """ if not self.lat or not self.lon: # we need lat/lon to find the weather at this location raise AttributeError( "Need to call get_geocode_data or set lat/lon manually") owm = OWM(current_app.config['WEATHER_API_KEY']) mgr = owm.weather_manager() self.weather = mgr.weather_at_coords(self.lat, self.lon).weather good_weather = ["few", "light", "scattered"] if any(x in self.weather.detailed_status.lower() for x in good_weather): self.weather_status = "clear" else: self.weather_status = "bad" return self.weather_status
def __get_observation_at_geocoords( api: OWM, location: dict) -> Tuple[Observation, UVIndex]: """ Gets the observation at a set of coordinates """ weather_manager = api.weather_manager() obs_weather: Observation = weather_manager.weather_at_coords( lat=location["latitude"], lon=location["longitude"]) if obs_weather is None: return LOC_NOT_FOUND_MSG uvindex_manager = api.uvindex_manager() obs_uv: UVIndex = uvindex_manager.uvindex_around_coords( obs_weather.location.lat, obs_weather.location.lon) return (obs_weather, obs_uv)