def weather_condition(place, interval): forecaster = open_weather_manager.forecast_at_place(place, interval) print(forecaster.will_have_fog()) print(forecaster.will_have_clouds()) print(forecaster.will_have_rain()) print(forecaster.will_be_rainy_at(timestamps.tomorrow(12))) print(forecaster.will_be_stormy_at(timestamps.tomorrow(12)))
async def forecast(self, ctx, a, t=None): comma = ',' mgr = owm.weather_manager() if comma in a: observation = mgr.forecast_at_place(a, '3h').forecast else: observation = mgr.forecast_at_place(a + ',US', '3h').forecast weather = observation.weather embedColor = random.randint(0, 0xffffff) if (t == 'f'): cf = 'fahrenheit' label = ' F' elif (t == 'fahrenheit'): cf = 'fahrenheit' label = ' F' elif (t == 'celsius'): cf = 'celsius' label = ' C' else: cf = 'celsius' label = ' C' tomorrow = timestamps.tomorrow() # datetime object for tomorrow weather = observation.get_weather_at(tomorrow) await ctx.send(weather)
def weather_detail(place, unit, hr, m): mgr = owm.weather_manager() forecaster = mgr.forecast_at_place(place, '3h') time = timestamps.tomorrow(hr, m) weather = forecaster.get_weather_at(time) t = weather.temperature(unit)['temp'] st.write( f"## Temperature at {place} for the selected time in {unit} is {t}") st.title(f"Expected Temperature Changes/Alerts at {hr}:{m}") if forecaster.will_be_foggy_at(time): st.write("### FOG ALERT!!") if forecaster.will_be_rainy_at(time): st.write("### RAIN ALERT!!") if forecaster.will_be_stormy_at(time): st.write("### STORM ALERT!!") if forecaster.will_be_snowy_at(time): st.write("### SNOW ALERT!!") if forecaster.will_be_tornado_at(time): st.write("### TORNADO ALERT!!") if forecaster.will_be_hurricane_at(time): st.write("### HURRICANE ALERT") if forecaster.will_be_clear_at(time): st.write("### CLEAR WEATHER PREDICTED!!") if forecaster.will_be_cloudy_at(time): st.write("### CLOUDY SKIES")
def test_tomorrow(self): now = datetime.now() tomorrow = date.today() + timedelta(days=1) result = timestamps.tomorrow() expected = datetime(tomorrow.year, tomorrow.month, tomorrow.day, now.hour, now.minute, 0) self.assertEqual(expected, result)
def forecast(city: str, timestamp: str): time_to_start = time.time() global programMetrics global processing_time_of_the_request_forecast_weather programMetrics[2] += 1 mgr = owm.weather_manager() observation = mgr.forecast_at_place( city, "3h" ) #данной командой стягивается прогноз погоды на ближайшие 5 дней с частотой 3 часа if timestamp == "1h": timest = timestamps.next_hour() elif timestamp == "3h": timest = timestamps.next_three_hours() elif timestamp == "tomorrow": timest = timestamps.tomorrow() elif timestamp == "yesterday": timest = timestamps.yesterday() else: timest = timestamps.now() w = observation.get_weather_at(timest) temp = w.temperature('celsius')['temp'] #вывод в консоль print(" request: " + city + "\ttime: " + str(timest) + "\t" + w.detailed_status + "\t" + str(temp)) processing_time_of_the_request_forecast_weather.append(time.time() - time_to_start) return json.dumps({ "city": city, "unit": "celsius", "temperature": temp, "id_service": my_id })
def get_forecast(city_id): forecast = manager.forecast_at_place( city_id, '3h') #change to forecast_at_id() to get use id tomorrow = timestamps.tomorrow() # datetime object for tomorrow clear_days = forecast.when_clear() most_rain = forecast.most_rainy() return most_rain, clear_days
def test_tomorrow_with_hour_and_minute(self): tomorrow = date.today() + timedelta(days=1) result = timestamps.tomorrow(18, 56) expected = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 18, 56, 0, 0, timezone.utc) self.assertEqual(expected, result) self.is_timezone_aware(result)
def test_tomorrow_with_hour_only(self): now = datetime.now(timezone.utc) tomorrow = date.today() + timedelta(days=1) result = timestamps.tomorrow(6) expected = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 6, now.minute, 0, 0, timezone.utc) self.assertEqual(expected, result) self.is_timezone_aware(result)
def storm_tomorrow(self) -> bool: """ Checks if it will be stormy tomorrow Returns: :return bool, True if stormy, False otherwise """ tomorrow = timestamps.tomorrow() return self.three_hour_forecast.will_be_stormy_at(tomorrow)
def rain_tomorrow(self) -> bool: """ Checks if it will rain tomorrow Returns: :return bool, True if it will be rainy, False otherwise """ tomorrow = timestamps.tomorrow() return self.three_hour_forecast.will_be_rainy_at(tomorrow)
def forecast_weather(self): forecast = self.mgr.forecast_at_place(f"{self.city},jp", '3h') w = forecast.get_weather_at(timestamps.tomorrow()) return { 'detailed_status': w.detailed_status, 'wind': w.wind(), 'humidity': w.humidity, 'temperature': w.temperature('celsius'), 'rain': w.rain, 'heat_index': w.heat_index, 'clouds': w.clouds, }
def weather_at_time(user_time, place, interval): open_weather_manager = open_weather_map.weather_manager() forecaster = open_weather_manager.forecast_at_place(place, interval) time = datetime.now() + timedelta(days = 0, hours=12) weather = forecaster.get_weather_at(time) temperature = weather.temperature(unit="fahrenheit")['temp'] print(f'The temperature at {time.strftime("%Y-%m-%d %H:%M:%S")} is {temperature}{degree_sign}F') time = timestamps.tomorrow(user_time,0) weather = forecaster.get_weather_at(time) temperature = weather.temperature(unit='fahrenheit')['temp'] print(f"The temperature at {time} is {temperature}{degree_sign}F")
def weather_forec(): voice_io.show("Sorry i am currently restricted to show weather forecast for tomorrow only. \nLook out for future updates and see if my handcuffs are set free. Here's tomorrow's weather forecast anyway.") owm = OWM(api) mgr=owm.weather_manager() loc = mgr.weather_at_place(ct) weather = loc.weather temp = weather.temperature(unit='celsius') for key,val in temp.items(): if key=="temp": voice_io.show(f'\nThe temperature tommorow will be around {val}°C.') else: continue loa = mgr.forecast_at_place(ct,'3h') tomorrow=timestamps.tomorrow() forecasttt=loa.get_weather_at(tomorrow) status=(forecasttt.status) voice_io.show(f'And the sky would remain {status}')
async def weather_slash( self, inter: discord.CommandInteraction, where: str = commands.Param(description="Place where show weather"), when: str = commands.Param( autocomplete=when_autocomplete, default="UTC Now", description="UTC Time offset of weather prediction")): when = when.lower() if when == "utc now": time = timestamps.now() elif when == "utc tomorrow": time = timestamps.tomorrow() else: if when.isnumeric(): when = int(when) else: if when[-1] != "h": return await inter.send( embed=general_util.generate_error_message( Strings.weather_slash_invalid_when_format), delete_after=Config.base_error_duration) when = int(when[:-1]) time = timestamps.now() + timestamps.timedelta(hours=when) try: weather = self.get_time_specific_weather(where, time) except commands.CommandOnCooldown: return await inter.send(embed=general_util.generate_error_message( Strings.weather_api_reached_minute_limit), delete_after=Config.base_error_duration) if weather is None: return await inter.send(embed=general_util.generate_error_message( Strings.populate_string("weather_failed_to_get_weather", place=where)), delete_after=Config.base_error_duration) embed = generate_weather_embed(weather, where) general_util.add_author_footer(embed, inter.author) await inter.send(embed=embed)
def weather_tomorrow(place: str) -> str: """Формирует ответ с погодой на завтрав городе с названием 'place' в случае если город отсутствует выдет соответствующую информационную строку""" mgr = owm.weather_manager() try: forecaster = mgr.forecast_at_place(place, '3h') except: return 'Place error' else: answer = f"Прогноз погоды в городе {place} на завтра:\n" for time in [9, 12, 15, 18, 21]: tomorrow_time = timestamps.tomorrow(time, 0) weather_in_time = forecaster.get_weather_at(tomorrow_time) answer += ( f"В {time}-00: {weather_in_time.detailed_status}, " f"t\xb0: {round(weather_in_time.temperature('celsius')['temp'])} C\xb0, " f"h: {weather_in_time.humidity} мм рт. ст., " f"ветер {deg_word(weather_in_time.wind()['deg'])} {weather_in_time.wind()['speed']} м/с.\n" ) return answer
async def weather_tomorrow(self, ctx: commands.Context, *, place: str): await general_util.delete_message(self.bot, ctx) try: weather = self.get_time_specific_weather(place, timestamps.tomorrow()) except commands.CommandOnCooldown: return await ctx.send(embed=general_util.generate_error_message( Strings.weather_api_reached_minute_limit), delete_after=Config.base_error_duration) if weather is None: return await ctx.send(embed=general_util.generate_error_message( Strings.populate_string("weather_failed_to_get_weather", place=place)), delete_after=Config.base_error_duration) embed = generate_weather_embed(weather, place) general_util.add_author_footer(embed, ctx.author) await ctx.send(embed=embed)
def forecast(city: str, timestamp: str): mgr = owm.weather_manager() observation = mgr.forecast_at_place( city, "3h" ) #данной командой стягивается прогноз погоды на ближайшие 5 дней с частотой 3 часа if timestamp == "1h": time = timestamps.next_hour() elif timestamp == "3h": time = timestamps.next_three_hours() elif timestamp == "tomorrow": time = timestamps.tomorrow() elif timestamp == "yesterday": time = timestamps.yesterday() else: time = timestamps.now() w = observation.get_weather_at(time) temp = w.temperature('celsius')['temp'] #вывод в консоль print(" request: " + city + "\ttime: " + str(time) + "\t" + w.detailed_status + "\t" + str(temp)) return json.dumps({"city": city, "unit": "celsius", "temperature": temp})
def getForecast(location, time): # Will it be clear tomorrow at this time in Milan (Italy) ? forecast = mgr.forecast_at_place('Milan,IT', 'daily') answer = forecast.will_be_clear_at(timestamps.tomorrow()) print(answer)
def display(request): try: city_name = request.POST['city'] obs = mgr.weather_at_place(city_name) weather = obs.weather weather_dict = { 'Clear': '맑음', 'Clouds': '흐림', 'Rain': '비', 'Thunderstorm': '폭풍우', 'Snow': '눈', 'Mist': '안개' } # 기온 temperature = weather.temperature('celsius') # 바람 관련 wind = weather.wind(unit='beaufort') wind_speed = wind['speed'] wind_deg = wind['deg'] # 풍속 (보퍼트 풍력 계급) if 0 <= wind_speed <= 4: wind_speed = '약한 바람' elif wind_speed <= 6: wind_speed = '조금 강한 바람' elif wind_speed <= 8: wind_speed = '강한 바람' elif wind_speed <= 12: wind_speed = '매우 강한 바람' # 풍향 if (0 <= wind_deg <= 10) or (340 < wind_deg <= 360): wind_deg = '북' elif 10 < wind_deg <= 30: wind_deg = '북북동' elif 30 < wind_deg <= 50: wind_deg = '북동' elif 50 < wind_deg <= 70: wind_deg = '동북동' elif 70 < wind_deg <= 100: wind_deg = '동' elif 100 < wind_deg <= 120: wind_deg = '동남동' elif 120 < wind_deg <= 140: wind_deg = '남동' elif 140 < wind_deg <= 160: wind_deg = '남남동' elif 160 < wind_deg <= 190: wind_deg = '남' elif 190 < wind_deg <= 210: wind_deg = '남남서' elif 210 < wind_deg <= 230: wind_deg = '남서' elif 230 < wind_deg <= 250: wind_deg = '서남서' elif 250 < wind_deg <= 280: wind_deg = '서' elif 280 < wind_deg <= 300: wind_deg = '서북서' elif 300 < wind_deg <= 320: wind_deg = '북서' elif 320 < wind_deg <= 340: wind_deg = '북북서' # 일출, 일몰 시간 sunrise = weather.sunrise_time(timeformat='date') sunrise += timedelta(hours=9) sunset = weather.sunset_time(timeformat='date') sunset += timedelta(hours=9) # 내일의 날씨 three_h_forecast = mgr.forecast_at_place(city_name, '3h') tomorrow = timestamps.tomorrow() tomorrow += timedelta(hours=9) tomorrow_weather = three_h_forecast.get_weather_at(tomorrow) # 내일 비가 옴? tomorrow_is_rain = '아뇽' rain_list = [] rain_flag = 1 for i in range(0, 24): time = i tomorrow_time = timestamps.tomorrow(time, 0) tomorrow_specific_weather = three_h_forecast.get_weather_at( tomorrow_time).status if tomorrow_specific_weather == 'Rain': rain_list.append(time) rain_flag = 0 if len(rain_list) != 0 and rain_flag == 0: if len(rain_list) == 1: tomorrow_is_rain = '넹 %d시에 옵니당' % rain_list[0] elif 2 <= len(rain_list): tomorrow_is_rain = '넹 %d시부터 %d시까지 옵니당' % (rain_list[0], rain_list[-1]) # 내일 눈이 옴? tomorrow_is_snow = '아뇽' snow_list = [] snow_flag = 1 for i in range(0, 24): time = i tomorrow_time = timestamps.tomorrow(time, 0) tomorrow_specific_weather = three_h_forecast.get_weather_at( tomorrow_time).status if tomorrow_specific_weather == 'Snow': snow_list.append(time) snow_flag = 0 if len(snow_list) != 0 and snow_flag == 0: if len(snow_list) == 1: tomorrow_is_snow = '넹 %d시에 옵니당' % snow_list[0] elif 2 <= len(snow_list): tomorrow_is_snow = '넹 %d시부터 %d시까지 옵니당' % (snow_list[0], snow_list[-1]) gmaps = googlemaps.Client( key='AIzaSyCmM3vFXEdl5yuuWqJApoxPF0H67jWqHAY') geocode_result = gmaps.geocode((city_name)) lat = geocode_result[0]['geometry']['location']['lat'] lng = geocode_result[0]['geometry']['location']['lng'] air_url = 'http://api.openweathermap.org/data/2.5/' \ 'air_pollution/forecast?lat=%f&lon=%f&appid=' % (lat, lng) mykey = 'a3a57abdc75d6bd277763f8062aa14cd' air_url += mykey r = requests.get(air_url) data = json.loads(r.text) pm10 = data['list'][0]['components']['pm10'] aqi = data['list'][0]['main']['aqi'] if 0 <= pm10 <= 30: pm10 = '좋음' elif 30 < pm10 <= 80: pm10 = '보통' elif 80 < pm10 <= 150: pm10 = '나쁨' elif 150 < pm10: pm10 = '매우 나쁨' if aqi == 1: aqi = '매우 좋음' elif aqi == 2: aqi = '좋음' elif aqi == 3: aqi = '보통' elif aqi == 4: aqi = '나쁨' elif aqi == 5: aqi = '매우 나쁨' ctx = { 'weather': weather_dict[weather.status], 'temperature': temperature['temp'], 'wind_speed': wind_speed, 'wind_deg': wind_deg, 'tomorrow_weather': weather_dict[tomorrow_weather.status], 'tomorrow_is_rain': tomorrow_is_rain, 'tomorrow_is_snow': tomorrow_is_snow, 'pm10': pm10, 'aqi': aqi, 'cityname': city_name, } except: return render(request, 'weather/citynameerror.html') return render(request, 'weather/displayweather.html', ctx)
owm = OWM('9a5b8a94e895ee75f75dee6ec42c3414') mgr = owm.weather_manager() observation_spb = mgr.weather_at_place("Saint Petersburg, RU") w_spb = observation_spb.weather tem_spb = w_spb.temperature("celsius")["temp"] observation_msk = mgr.weather_at_place("Moscow, RU") w_msk = observation_msk.weather tem_msk = w_msk.temperature("celsius")["temp"] observation_don = mgr.weather_at_place("Donetsk, UA") w_don = observation_don.weather tem_don = w_don.temperature("celsius")["temp"] tomorrow_at_midnight = timestamps.tomorrow(0, 0) tomorrow_at_three_night = timestamps.tomorrow(3, 0) tomorrow_at_six_morning = timestamps.tomorrow(6, 0) tomorrow_at_nine_morning = timestamps.tomorrow(9, 0) tomorrow_at_mid = timestamps.tomorrow(12, 0) tomorrow_at_three = timestamps.tomorrow(15, 0) tomorrow_at_six = timestamps.tomorrow(18, 0) tomorrow_at_nine = timestamps.tomorrow(21, 0) three_h_forecaster = mgr.forecast_at_place('Saint Petersburg', '3h') sweather_tomorrow = three_h_forecaster.get_weather_at(tomorrow_at_midnight).temperature("celsius")["temp"] sweather_tomorrow1 = three_h_forecaster.get_weather_at(tomorrow_at_three_night).temperature("celsius")["temp"] sweather_tomorrow2 = three_h_forecaster.get_weather_at(tomorrow_at_six_morning).temperature("celsius")["temp"] sweather_tomorrow3 = three_h_forecaster.get_weather_at(tomorrow_at_nine_morning).temperature("celsius")["temp"] sweather_tomorrow4 = three_h_forecaster.get_weather_at(tomorrow_at_mid).temperature("celsius")["temp"] sweather_tomorrow5 = three_h_forecaster.get_weather_at(tomorrow_at_three).temperature("celsius")["temp"]
import pyowm from pyowm.utils import timestamps from datetime import timedelta, datetime owm = pyowm.OWM('d90703eea69f90f613b88279fea113db') mgr = owm.weather_manager() place = input("Enter the name of your city: ") forecaster = mgr.forecast_at_place(place, '3h') print("Stormy: " + str(forecaster.will_be_stormy_at(timestamps.tomorrow(15, 0)))) print("Foggy: " + str(forecaster.will_be_stormy_at(timestamps.tomorrow(12, 0)))) print("Clear-Sky: " + str(forecaster.will_be_stormy_at(timestamps.tomorrow(8, 30))))
import pyowm from pyowm.utils import timestamps from datetime import timedelta, datetime degree_sign = u'\N{DEGREE SIGN}' owm = pyowm.OWM('d90703eea69f90f613b88279fea113db') mgr = owm.weather_manager() forecaster = mgr.forecast_at_place('Los Angeles, US', '3h') time = datetime.now() + timedelta(days=0, hours=12) weather = forecaster.get_weather_at(time) temperature = weather.temperature(unit='fahrenheit')['temp'] print( f'The temperature at {time.strftime("%Y-%m-%d %H:%M:%S")} is {temperature}{degree_sign}F' ) time = timestamps.tomorrow(15, 0) weather = forecaster.get_weather_at(time) temperature = weather.temperature(unit='fahrenheit')['temp'] print(f'The temperature at {time} is {temperature}{degree_sign}F')
# ---------- FREE API KEY examples --------------------- owm = OWM('your free OWM API key') mgr = owm.weather_manager() # Search for current weather in London (Great Britain) and get details observation = mgr.weather_at_place('London,GB') w = observation.weather w.detailed_status # 'clouds' w.wind() # {'speed': 4.6, 'deg': 330} w.humidity # 87 w.temperature('celsius') # {'temp_max': 10.5, 'temp': 9.7, 'temp_min': 9.0} w.rain # {} w.heat_index # None w.clouds # 75 # Will it be clear tomorrow at this time in Milan (Italy) ? forecast = mgr.forecast_at_place('Milan,IT', 'daily') answer = forecast.will_be_clear_at(timestamps.tomorrow()) # ---------- PAID API KEY example --------------------- config_dict = config.get_default_config_for_subscription_type('professional') owm = OWM('your paid OWM API key', config_dict) # What's the current humidity in Berlin (Germany) ? one_call_object = mgr.one_call(lat=52.5244, lon=13.4105) one_call_object.current.humidity
# ---------- FREE API KEY --------------------- owm = OWM('your-API-key') # You MUST provide a valid API key # Search for current weather in London (Great Britain) mgr = owm.weather_manager() observation = mgr.weather_at_place('London,GB') w = observation.weather print(w) # <Weather - reference time=2013-12-18 09:20, status=Clouds> # Weather details w.wind() # {'speed': 4.6, 'deg': 330} w.humidity # 87 w.temperature('celsius') # {'temp_max': 10.5, 'temp': 9.7, 'temp_min': 9.0} # Search current weather observations in the surroundings of # lat=22.57W, lon=43.12S (Rio de Janeiro, BR) observation_list = mgr.weather_around_coords(-22.57, -43.12) # ---------- PAID API KEY --------------------- config_dict = config.get_default_config_for_subscription_type('professional') owm = OWM('your-paid-api-key', config_dict) # Will it be clear tomorrow at this time in Milan (Italy) ? mgr = owm.weather_manager() forecast = mgr.forecast_at_place('Milan,IT', 'daily') forecast.will_be_clear_at(timestamps.tomorrow()) # The sun always shines on Italy, right? ;)
import pyowm from pyowm.utils import timestamps from datetime import timedelta, datetime from api_key import API_KEY owm = pyowm.OWM(API_KEY) mgr = owm.weather_manager() forecaster = mgr.forecast_at_place('Los Angeles, US', '3h') # Write your code here date1 = timestamps.tomorrow(12, 0) date2 = timestamps.tomorrow(8, 30) print(forecaster.will_be_foggy_at(date1)) print(forecaster.will_be_clear_at(date2))
from pyowm.owm import OWM from pyowm.utils.config import get_default_config from pyowm.utils import timestamps config_dict = get_default_config() config_dict['language'] = 'ru' # owm = OWM('e7bb679b81c3710fc4192bcc1018a907') owm = OWM('70732ac514bf006244ac74c5f31de5aa', config_dict) mgr = owm.weather_manager() # daily_forecast = mgr.forecast_at_place('Berlin,DE', 'daily').forecast three_h_forecast = mgr.forecast_at_place('Moscow,RU', '3h').forecast # print(daily_forecast) # print(three_h_forecast) # nr_of_weathers = len() three_forecaster = mgr.forecast_at_place('Moscow,RU', '3h') tomorrow_at_five = timestamps.tomorrow(17, 0) weather = three_forecaster.get_weather_at(tomorrow_at_five) # print(weather.status) # print(weather.detailed_status) # print(weather.status) print(dir(mgr.forecast_at_place('Moscow,RU', 'daily')))