def predict(): # fetch the current forecast config = getConfig('config.ini') OWM_API_key = config.get('config', 'OWM_API_key').encode('ascii') OWM_location = config.get('config', 'OWM_location').encode('ascii') owm = OWM(OWM_API_key) fc = owm.daily_forecast(OWM_location, limit=3) f = fc.get_forecast() predictions = [] for w in f: # Figure out if the sun is up(probably important) daytime = 'f' currTime = w.get_reference_time() sunriseTime = w.get_sunrise_time() sunsetTime = w.get_sunset_time() if(currTime > sunriseTime and currTime < sunsetTime): daytime = 't' result = powerProduction.query.filter_by(daytime='t', status=w.get_status()) weatherData = [] powerData = [] for r in result: weatherData.append([r.cloudCover, r.windSpeed, r.humidity, r.pressure, r.temperature]) powerData.append([r.powerLevel]) # perform multivariate linear regression on the data to find the correlation between weather and power production model = linear_model.LinearRegression() model.fit(weatherData,powerData) cloudCover = w.get_clouds() windSpeed = 0 humidity = w.get_humidity() pressure = w.get_pressure()['press'] temperature = w.get_temperature(unit='celsius')['day'] status = w.get_status() currentWeather = array([cloudCover, windSpeed, humidity, pressure, temperature]) # use the regression model to generate production predictions based on the current forecast # print "Predicted power production: " + str(model.predict(currentWeather)) predictions.append(model.predict(currentWeather)) print "predictor run..." return predictions
def weather(): # create OWM object API_key = '3ca51794f7789141f0525a05d80a43b9' owm = OWM(API_key) theCity = "Seattle" theState = "WA" weatherCityState = theCity + ", " + theState weatherLocation = theCity + ",US" # get currently observed weather for Seattle, WA, US obs = owm.weather_at_place(weatherLocation) # get weather object for current Seattle weather w = obs.get_weather() # get current weather status and temperature in fahrenheit currStatus = w.get_detailed_status() tempF = w.get_temperature('fahrenheit')["temp"] # query the daily forcast for Seattle, WA, US, for the next 5 days fc = owm.daily_forecast('Seattle,US', limit=5) # get a forcaster object f = fc.get_forecast() return render_template('templateWeather.html', theLocation=weatherCityState, currStatus=currStatus, theTemp=tempF, forecast=f, title="Weather", arrow=arrow)
class Weather(PluginBase): def __init__(self): self._owm = OWM(os.environ['OWM_API_KEY']) def execute(self, args): if len(args) != 1: raise ValueError('wrong number of arguments are given') location = args[0] result = '' for weather in self._owm.daily_forecast(location, 7).get_forecast(): result += '{:s} {:s}\n'.format(weather.get_reference_time('iso'), weather.get_status()) return result def help(self): return 'location\n' \ 'Print current weather observations and forecast'
def get_weather(place): api_key = '4becd4f5bd426b1adc8d23b8496d7d00' owm = OWM(api_key) owm_en = OWM() observation = owm.weather_at_place(place) temp = observation.get_weather().get_temperature('fahrenheit') daily_forecasts = owm.daily_forecast(place).get_forecast() print(temp) print() for forecast in daily_forecasts: date = forecast.get_reference_time('iso') status = forecast.get_status() temps = forecast.get_temperature('fahrenheit') print(date, status, temps) return temp
mirf = MirfBase() mirf.try_cache(60 * 15) degrees = str(chr(223)) apikey = None with open(mydir + "/.api-key-openweathermap", "rb") as apifile: apikey = apifile.readline().strip() owm = OWM(apikey) placename = '20017,US' wap = owm.weather_at_place(placename) w = wap.get_weather() fc = owm.daily_forecast(placename, limit=1) outputConditions = "C" outputNow = "N" outputLater = "L" output1 = "0 " output2 = "1 " status = w.get_status() detailedStatus = w.get_detailed_status().capitalize() temp = w.get_temperature(unit='fahrenheit') tempnow = temp['temp'] tempmin = temp['temp_min'] tempmax = temp['temp_max']
from pyowm import OWM parser = argparse.ArgumentParser() parser.add_argument('--owmkey', help='API key to http://openweathermap.org/', required=True) parser.add_argument('--city', help='City', default='Wroclaw, PL') args = parser.parse_args() owm = OWM(language='en', API_key=args.owmkey, version='2.5') icons = [] icons_parse = [] highs = [] lows = [] dates = [] forecast = owm.daily_forecast(args.city, limit=4).get_forecast() for weather in forecast: # Parse icons icons.append(weather.get_weather_code()) # Parse temperature highs highs.append(round(weather.get_temperature(unit='celsius')['max'], 1)) # Parse temperature lows lows.append(round(weather.get_temperature(unit='celsius')['min'], 1)) # Parse dates dates.append(weather.get_reference_time('iso')[:-12]) # Parse date day_one = datetime.datetime.strptime(str(dates[0]), '%Y-%m-%d') # Change icons from OWM format to the format the svg wants them in. This is
mirf = MirfBase() mirf.try_cache(60*15) degrees = str(chr(223)) apikey=None with open(mydir + "/.api-key-openweathermap", "rb") as apifile: apikey = apifile.readline().strip() owm = OWM(apikey) placename='20017,US' wap = owm.weather_at_place(placename) w = wap.get_weather() fc = owm.daily_forecast(placename, limit=1) outputConditions = "C" outputNow = "N" outputLater = "L" output1 = "0 " output2 = "1 " status = w.get_status() detailedStatus = w.get_detailed_status().capitalize() temp = w.get_temperature(unit='fahrenheit') tempnow = temp['temp'] tempmin = temp['temp_min'] tempmax = temp['temp_max']
def get_forecast(location, days): owm = OWM(WEATHER_API_KEY) daily_forecast = owm.daily_forecast(location, limit=days) forecast_data = daily_forecast.get_forecast() return forecast(forecast_data)
class WeatherForecastService: def __init__(self, language="en"): self._api = OWM(OWM_API_KEY, language=language) self.set_language(language) def set_language(self, language): """ Sets _language for OWM API. :param language : _language code (str) e.g. en, fr, sr... :return: """ logger.debug("Setting owm _language: {}".format(language)) language = 'hr' if language == 'sr' else language self._api.set_language(language) # region public methods def get_forecast_result(self, location, param="all", unit="celsius"): """ Returns weather forecast for location. :param location: location (str) - location which forecast we seek :param param: param (str); default = all - which weather parameter we want :param unit: unit(str); default = celsius - unit for temperature measurement, expected values are celsius, fahrenheit and kelvin :return: weather forecast in string format weather_param:value covered params:clouds, pressure, wind speed (mph), humidity, minimum temperature, maximum temperature,temperature detailed status """ logger.debug( "Calling get_forecast_result with params: [location = {}, param = {}, unit = {}]".format(str(location), \ str(param), str(unit))) weather_data = self._get_weather_at_location(location) logger.debug("Weather data results were fetched....") logger.debug("Raw forecast results = {}".format(str(weather_data))) forecast_output = self._get_forecast_in_readable_form( weather_data, param, **{"unit": unit}) logger.debug("Forecast in readable form:\n{}".format(forecast_output)) return ActionResult(forecast_output, SUCCESS) # region private methods @lru_cache(maxsize=8) def _get_weather_at_location(self, location, out_format="json"): """ Get raw weather data. :param location: location (str) - location which forecast we seek :param out_format: output format (str) - (json, xml) :return: returns observation object (pyowm.weatherapi25.observation.Observation) """ assert (out_format in ("json", "xml")), "Only json and xml output formats are supported!" if type(location) == str: target_function = self._api.weather_at_place elif type(location) == int: target_function = self._api.weather_at_id elif type(location) == tuple: # NOTE:do not use tuple, currently it is not handled when lat,long tuple arg is used target_function = self._api.weather_at_coords else: raise TypeError("Location type_ is not valid.") weather_data = target_function(location) return weather_data.get_weather() def _get_forecast_in_readable_form(self, weather_data, param_name, **kwargs): """ Returns weather forecast in for-read user-friendly form. :param weather_data (pyowm.weatherapi25.weather.Weather): Weather object :param param_name (str): parameter we want e.g. temperature, humidity,.... metric units: wind (m/s), temperature (celsius), cloudines(%), pressure(mbar), humidity... :param kwargs: :return: weather data in string format weather_param:value """ forecast = self._get_forecast(weather_data, param_name, **kwargs) logger.debug("Complete forecast info: {}".format(forecast)) display_str = '' for param, struct in WEATHER_PARAMETERS.items(): if param in ("temperature_min", "temperature_max"): param = "temperature" if param not in forecast: continue # NOTE:pressure value is measured in hPa, which is equal to mbar weather_param_value = forecast[param] if param == "reference_time": weather_param_value = datetime.utcfromtimestamp( int(weather_param_value)).strftime('%d-%m-%Y %H:%M:%S') child_alias_status = struct[1] child_alias_value = struct[0] display_name = struct[2][self._api.get_language()] value = weather_param_value[ child_alias_value] if child_alias_status == "child" else weather_param_value display_str += display_name + ": " + str(value) + ",\n" return display_str def _get_forecast(self, weather_data, param, **kwargs): """ Get weather parameter dictionary from weather object. If param is `all`, then returns complete weather status, with all parameters defined in config file :param weather_data (pyowm.weatherapi25.weather.Weather): Weather object :param param_name (str): parameter we want e.g. temperature, humidity,.... :param kwargs: :return: dictionary with weather_param:value pairs """ if param == "all": weather_param = self._get_all_weather_params( weather_data, **kwargs) else: weather_param = self._get_weather_param(weather_data, param, **kwargs) return weather_param def _get_all_weather_params(self, weather_data, **kwargs): """ Returns complete weather status, with all parameters defined in config file. :param weather_data (pyowm.weatherapi25.weather.Weather): Weather object :return: dictionary with weather_param:value pairs """ weather = {} for param in WEATHER_PARAMS: weather.update( self._get_weather_param(weather_data, param, **kwargs)) return weather def _get_weather_param(self, weather_data, param, **kwargs): """ Get weather parameter dictionary from weather object for particular weather param. :param weather_data (pyowm.weatherapi25.weather.Weather): Weather object :param param_name (str): parameter we want e.g. temperature, humidity,.... :param kwargs: :return: dictionary with weather_param:value pair to follow usage interface in higher level methods """ func_ptr = weather_param = None if hasattr(weather_data, 'get_' + param): func_ptr = getattr(weather_data, 'get_' + param) if func_ptr is not None: if param == 'temperature' and kwargs.get('unit', None) is not None: unit = kwargs.get('unit', None) if unit not in ( "celsius", "fahrenheit" ): # imperial = fahrenheit, metric = celsius, kelvin is by default raise ValueError( "Only celsius, kelvin and fahrenheit scales are supported" ) weather_param = func_ptr(unit=unit) else: weather_param = func_ptr() return {param: weather_param} # for weather prediction - not used at this moment def _get_forecast_for_next_x_days(self, location, days_limit): forecast = self._api.daily_forecast(location, limit=days_limit) return forecast # _get_forecast and get_weather_at
import urllib2 from xml.dom import minidom import datetime import codecs from pprint import pprint from pyowm import OWM api_key = '4c2f530274356fa51b07af049c960ed9' city = 'Warsaw,PL' owm = OWM(api_key) obs = owm.weather_at_place(city) # w = obs.get_weather() fc = owm.daily_forecast(city) f = fc.get_forecast() highs = [None]*4 lows = [None]*4 icons = [None]*4 iconsMap = {'802': 'bkn', '801': 'bkn', 601: 'sn', 602: 'blizzard', 611: 'sn', 612: 'sn', 741: 'fg', 701: 'fg', 721: 'fg', 500: 'hi_shwrs', 501: 'hi_shwrs', 502: 'hi_shwrs', 503: 'hi_shwrs', 803: 'ovc', 804: 'ovc', 300: 'ra', 301: 'ra', 302: 'ra', 310: 'ra', 311: 'ra', 312: 'ra', 313: 'ra', 314: 'ra', 321: 'ra', 903: 'cold', 511: 'fzra', 904: 'hot', 210: 'scttsra', 201: 'scttsra', 202: 'scttsra', 211: 'scttsra', 212: 'scttsra', 221: 'scttsra', 230: 'scttsra', 231: 'scttsra', 232: 'scttsra', 800: 'skc', 600: 'sn', 200: 'tsra', 905: 'wind', 957: 'wind', 801: 'few', 616: 'mix', 621: 'mix', 622: 'mix', 615: 'rasn', 620: 'rasn', 802: 'ovc', }
owm = OWM(apikey) api_connect = checkAPI() if api_connect is True: payload = {'fields': 'countryCode,regionName,city'} response = requests.get('http://ip-api.com/json/', params=payload) data = response.content # print(response.text, response.content) output = json.loads(data) city = output['city'] region_name = output['regionName'] country_code = output['countryCode'] search = ', '.join([city, region_name, country_code]) # print(search) forecast = owm.daily_forecast(search) observation = owm.weather_at_place(search) weather = observation.get_weather() status = str(weather.get_status().title()) detailed_status = str(weather.get_detailed_status().title()) unit_transfer = {"C": 'celsius', "F": 'fahrenheit', 'K': 'kelvin'} search_units = unit_transfer[units] temp = round(weather.get_temperature(search_units)['temp'], decimals) if decimals == 0: temp = int(float(temp)) temp = str(temp) # print(temp) outputs = [api_connect, temp, status, city, units, showunits, decimals] for n in range(len(outputs)):
class MyMainGui(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MyMainGui, self).__init__(parent) self.setupUi(self) app.setStyle(QStyleFactory.create('Plastique')) API_key = '1330050f05c5c2c1f05e678136d1ebc2' self.owm = OWM(API_key) # get a list of countries and alpha2 codes self.countries_list, self.alpha2_code_list = countries_list_and_code() self.comboBox_country.addItems(self.countries_list) self.toolButton_search.clicked.connect(self.search_city) self.lineEdit_city.returnPressed.connect(self.search_city) self.toolButton_next.clicked.connect(self.next_page_of_three_hour_display) self.toolButton_previous.clicked.connect(self.previous_page_of_three_hour_display) self.toolButton_previous.setDisabled(True) self.three_hour_display_page_number = 1 # disable the line below if you don't want to load weather for Berlin at start up self.initialize_display() def initialize_display(self): """Display weather for Berlin, Deustchland at startup""" self.search_query = "Berlin, DE" self.obs = self.owm.weather_at_place(self.search_query) self.lineEdit_city.setText("Berlin") self._display_five_day_forecast() self._make_three_hour_data() self._print_info() self.progressBar.setValue(0) def search_city(self): """Retrieves 5-day and 3-hourly data from OpenWeatherMap and then displays it in the GUI. Also updates progress bar while the data is being retrieved.""" self.selected_country_name = self.comboBox_country.currentText() self.country_index = self.comboBox_country.currentIndex() self.city = self.lineEdit_city.text() if not self.selected_country_name == "Select a country to refine your search (optional)": self.selected_country_alpha2_code = self.alpha2_code_list[self.country_index-1] self.search_query = self.city + ',' + self.selected_country_alpha2_code else: self.search_query = self.city print(self.search_query) self.progressBar.setValue(25) self.obs = self.owm.weather_at_place(self.search_query) self.progressBar.setValue(50) self._display_five_day_forecast() self.progressBar.setValue(75) self._make_three_hour_data() self._print_info() self.progressBar.setValue(100) def _print_info(self): """Populates the fields -- such as longitude, latitude, windspeed, etc. -- in the top right corner of the GUI. It also updates city name and country name.""" country_alpha2 = self.obs._location._country try: country_index = self.alpha2_code_list.index(country_alpha2) country_name = self.countries_list[country_index] except: country_name = country_alpha2 time_reference = str(datetime.fromtimestamp(self.obs._weather._reference_time)) self.label_date.setText(time_reference[8:10] + '/' + time_reference[5:7] + '/' + time_reference[0:4]) self.label_time.setText(time_reference[10:16]) longitude = str(self.obs._location._lon) latitude = str(self.obs._location._lat) city = self.obs._location._name summary = self.obs._weather._detailed_status # few clouds, heavy rain etc. sunrise_time_unix = self.obs._weather._sunrise_time # unix time sunset_time_unix = self.obs._weather._sunset_time sunrise_time = str(datetime.fromtimestamp(sunrise_time_unix)) sunset_time = str(datetime.fromtimestamp(sunset_time_unix)) humiditiy = str(self.obs._weather._humidity) + ' %' wind = self.obs._weather._wind wind_speed = str(wind['speed']) + ' m/s' try: wind_direction = str(wind['deg']) + ' Deg' # sometimes wind direction is not available except Exception as e: wind_direction = 'N/A' pressure_sea_and_press = self.obs._weather._pressure pressure = str(pressure_sea_and_press['press']) + ' hpa' visibility_distance = str(self.obs._weather._visibility_distance) + ' m' self.label_country.setText(country_name) self.label_city.setText(city) self.label_longitude.setText(str(longitude)) self.label_latitude.setText(str(latitude)) self.label_summary.setText(string.capwords(summary)) self.label_sunrise.setText(sunrise_time[11:16]) self.label_sunset.setText(sunset_time[11:16]) self.label_humidity.setText(humiditiy) self.label_wind_speed.setText(wind_speed) self.label_direction.setText(wind_direction) self.label_pressure.setText(pressure) self.label_visibility.setText(visibility_distance) def _display_five_day_forecast(self): """Retrieves five-day forecast and then populates this data in all the GUI fields of 5-day forecast Tab.""" self.fd = self.owm.daily_forecast(name=self.search_query, limit = 5) # day 1 day1 = self.fd._forecast._weathers[0] datetime_unix = day1._reference_time dtu = datetime.fromtimestamp(datetime_unix) day_of_the_week = dtu.strftime("%A") self.label_5day_day1.setText(day_of_the_week) dtu= str(dtu) self.label_5day_day1_date.setText(dtu[8:10] + '/' + dtu[5:7] + '/' + dtu[0:4]) self.label_5day_day1_desc.setText(string.capwords(day1._status)) icon_path = ':/icons/' + day1._weather_icon_name + '.png' icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_5day_day1_pic.setIcon(icon) self.label_5day_day1_min.setText(str(round(day1._temperature['min'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day1_max.setText(str(round(day1._temperature['max'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day1_morn.setText(str(round(day1._temperature['morn'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day1_day.setText(str(round(day1._temperature['day'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day1_even.setText(str(round(day1._temperature['eve'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day1_night.setText(str(round(day1._temperature['night'] - 273.15, 2)) + ' \u00b0C') # day 2 day2 = self.fd._forecast._weathers[1] datetime_unix = day2._reference_time dtu = datetime.fromtimestamp(datetime_unix) day_of_the_week = dtu.strftime("%A") dtu= str(dtu) self.label_5day_day2_date.setText(dtu[8:10] + '/' + dtu[5:7] + '/' + dtu[0:4]) self.label_5day_day2.setText(day_of_the_week) self.label_5day_day2_desc.setText(string.capwords(day2._status)) icon_path = ':/icons/' + day2._weather_icon_name + '.png' icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_5day_day2_pic.setIcon(icon) self.label_5day_day2_min.setText(str(round(day2._temperature['min'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day2_max.setText(str(round(day2._temperature['max'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day2_morn.setText(str(round(day2._temperature['morn'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day2_day.setText(str(round(day2._temperature['day'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day2_even.setText(str(round(day2._temperature['eve'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day2_night.setText(str(round(day2._temperature['night'] - 273.15, 2)) + ' \u00b0C') # day 3 day3 = self.fd._forecast._weathers[2] datetime_unix = day3._reference_time dtu = datetime.fromtimestamp(datetime_unix) day_of_the_week = dtu.strftime("%A") dtu= str(dtu) self.label_5day_day3_date.setText(dtu[8:10] + '/' + dtu[5:7] + '/' + dtu[0:4]) self.label_5day_day3.setText(day_of_the_week) self.label_5day_day3_desc.setText(string.capwords(day3._status)) icon_path = ':/icons/' + day3._weather_icon_name + '.png' icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_5day_day3_pic.setIcon(icon) self.label_5day_day3_min.setText(str(round(day3._temperature['min'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day3_max.setText(str(round(day3._temperature['max'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day3_morn.setText(str(round(day3._temperature['morn'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day3_day.setText(str(round(day3._temperature['day'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day3_even.setText(str(round(day3._temperature['eve'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day3_night.setText(str(round(day3._temperature['night'] - 273.15, 2)) + ' \u00b0C') # day 4 day4 = self.fd._forecast._weathers[3] datetime_unix = day4._reference_time dtu = datetime.fromtimestamp(datetime_unix) day_of_the_week = dtu.strftime("%A") dtu= str(dtu) self.label_5day_day4_date.setText(dtu[8:10] + '/' + dtu[5:7] + '/' + dtu[0:4]) self.label_5day_day4.setText(day_of_the_week) self.label_5day_day4_desc.setText(string.capwords(day4._status)) icon_path = ':/icons/' + day4._weather_icon_name + '.png' icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_5day_day4_pic.setIcon(icon) self.label_5day_day4_min.setText(str(round(day4._temperature['min'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day4_max.setText(str(round(day4._temperature['max'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day4_morn.setText(str(round(day4._temperature['morn'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day4_day.setText(str(round(day4._temperature['day'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day4_even.setText(str(round(day4._temperature['eve'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day4_night.setText(str(round(day4._temperature['night'] - 273.15, 2)) + ' \u00b0C') # day 5 day5 = self.fd._forecast._weathers[4] datetime_unix = day5._reference_time dtu = datetime.fromtimestamp(datetime_unix) day_of_the_week = dtu.strftime("%A") dtu= str(dtu) self.label_5day_day5_date.setText(dtu[8:10] + '/' + dtu[5:7] + '/' + dtu[0:4]) self.label_5day_day5.setText(day_of_the_week) self.label_5day_day5_desc.setText(string.capwords(day5._status)) icon_path = ':/icons/' + day5._weather_icon_name + '.png' icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_5day_day5_pic.setIcon(icon) self.label_5day_day5_min.setText(str(round(day5._temperature['min'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day5_max.setText(str(round(day5._temperature['max'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day5_morn.setText(str(round(day5._temperature['morn'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day5_day.setText(str(round(day5._temperature['day'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day5_even.setText(str(round(day5._temperature['eve'] - 273.15, 2)) + ' \u00b0C') self.label_5day_day5_night.setText(str(round(day5._temperature['night'] - 273.15, 2)) + ' \u00b0C') def _make_three_hour_data(self): """Retrieves three-hourly forecast.""" self.fc= self.owm.three_hours_forecast(self.search_query) self.weathers = self.fc._forecast._weathers self.weather_list = [] for i in range(0, self.weathers.__len__()): w = self.weathers[i] self.weather_list.append(w) self._display_three_hour_data() def next_page_of_three_hour_display(self): """Displays three-hourly forecast for the next 8 data points.""" if self.three_hour_display_page_number < 5: self.three_hour_display_page_number += 1 self._display_three_hour_data() if self.three_hour_display_page_number == 4: self.toolButton_next.setDisabled(True) else: self.toolButton_next.setDisabled(False) if not self.three_hour_display_page_number == 1: self.toolButton_previous.setDisabled(False) self._update_page_number() def previous_page_of_three_hour_display(self): """Displays three-hourly forecast for the previous 8 data points.""" if self.three_hour_display_page_number > 1: self.three_hour_display_page_number -= 1 self._display_three_hour_data() if self.three_hour_display_page_number == 1: self.toolButton_previous.setDisabled(True) else: self.toolButton_next.setDisabled(False) self._update_page_number() def _update_page_number(self): """Updates page numbers while the user is pressing next and previous buttons""" if self.three_hour_display_page_number == 1: self.label_page_number.setText("Page 1 of 4") elif self.three_hour_display_page_number == 2: self.label_page_number.setText("Page 2 of 4") elif self.three_hour_display_page_number == 3: self.label_page_number.setText("Page 3 of 4") elif self.three_hour_display_page_number == 4: self.label_page_number.setText("Page 4 of 4") def _display_three_hour_data(self): """This function displays the three-hourly weather data at various location in the 3-hour forecast Tab""" if self.three_hour_display_page_number == 1: data = self.weather_list[0] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_0_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[1] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_1_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[2] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_2_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[3] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_3_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[4] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_4_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[5] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_5_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[6] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_6_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[7] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_7_location(time, date, icon_path, min_temp, max_temp) if self.three_hour_display_page_number == 2: data = self.weather_list[8] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_0_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[9] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_1_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[10] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_2_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[11] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_3_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[12] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_4_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[13] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_5_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[14] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_6_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[15] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_7_location(time, date, icon_path, min_temp, max_temp) if self.three_hour_display_page_number == 3: data = self.weather_list[16] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_0_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[17] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_1_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[18] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_2_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[19] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_3_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[20] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_4_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[21] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_5_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[22] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_6_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[23] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_7_location(time, date, icon_path, min_temp, max_temp) if self.three_hour_display_page_number == 4: data = self.weather_list[24] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_0_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[25] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_1_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[26] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_2_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[27] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_3_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[28] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_4_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[29] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_5_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[30] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_6_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[31] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_7_location(time, date, icon_path, min_temp, max_temp) if self.three_hour_display_page_number == 5: data = self.weather_list[32] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_0_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[33] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_1_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[34] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_2_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[35] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_3_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[36] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_4_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[37] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_5_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[38] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_6_location(time, date, icon_path, min_temp, max_temp) data = self.weather_list[39] time, date, icon_path, min_temp, max_temp = self._get_relevent_data(data) self._display_in_7_location(time, date, icon_path, min_temp, max_temp) def _get_relevent_data(self, data): """A convenience function to time data and temperature in proper format.""" datetime_unix = data._reference_time dtu = str(datetime.fromtimestamp(datetime_unix)) date = dtu[8:10] + '/' + dtu[5:7] + '/' + dtu[0:4] time = dtu[11:16] min_temp = str(round(data._temperature['temp_min'] - 273.15, 2)) + ' \u00b0C' max_temp = str(round(data._temperature['temp_max'] - 273.15, 2)) + ' \u00b0C' icon_path = ':/icons/' + data._weather_icon_name + '.png' return time, date, icon_path, min_temp, max_temp def _display_in_0_location(self, time, date, icon_path, min_temp, max_temp): """Sets text and icons in the 0th location in 3-hour forecast tab""" self.label_0_time.setText(time) self.label_0_date.setText(date) icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_0_pic.setIcon(icon) self.label_0_min.setText(min_temp) self.label_0_max.setText(max_temp) def _display_in_1_location(self, time, date, icon_path, min_temp, max_temp): """Sets text and icons in the 1st location in 3-hour forecast tab""" self.label_1_time.setText(time) self.label_1_date.setText(date) icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_1_pic.setIcon(icon) self.label_1_min.setText(min_temp) self.label_1_max.setText(max_temp) def _display_in_2_location(self, time, date, icon_path, min_temp, max_temp): """Sets text and icons in the 2nd location in 3-hour forecast tab""" self.label_2_time.setText(time) self.label_2_date.setText(date) icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_2_pic.setIcon(icon) self.label_2_min.setText(min_temp) self.label_2_max.setText(max_temp) def _display_in_3_location(self, time, date, icon_path, min_temp, max_temp): """Sets text and icons in the 3rd location in 3-hour forecast tab""" self.label_3_time.setText(time) self.label_3_date.setText(date) icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_3_pic.setIcon(icon) self.label_3_min.setText(min_temp) self.label_3_max.setText(max_temp) def _display_in_4_location(self, time, date, icon_path, min_temp, max_temp): """Sets text and icons in the 4th location in 3-hour forecast tab""" self.label_4_time.setText(time) self.label_4_date.setText(date) icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_4_pic.setIcon(icon) self.label_4_min.setText(min_temp) self.label_4_max.setText(max_temp) def _display_in_5_location(self, time, date, icon_path, min_temp, max_temp): """Sets text and icons in the 5th location in 3-hour forecast tab""" self.label_5_time.setText(time) self.label_5_date.setText(date) icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_5_pic.setIcon(icon) self.label_5_min.setText(min_temp) self.label_5_max.setText(max_temp) def _display_in_6_location(self, time, date, icon_path, min_temp, max_temp): """Sets text and icons in the 6th location in 3-hour forecast tab""" self.label_6_time.setText(time) self.label_6_date.setText(date) icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_6_pic.setIcon(icon) self.label_6_min.setText(min_temp) self.label_6_max.setText(max_temp) def _display_in_7_location(self, time, date, icon_path, min_temp, max_temp): """Sets text and icons in the 7th location in 3-hour forecast tab""" self.label_7_time.setText(time) self.label_7_date.setText(date) icon = QIcon() icon.addPixmap(QPixmap(icon_path)) self.toolButton_7_pic.setIcon(icon) self.label_7_min.setText(min_temp) self.label_7_max.setText(max_temp)
def __init__(self): API = 'd71c3a62822470f2ecd05e06f214ecf5' CITY = 'Saint-Gely-du-Fesc' ''' Pour avoir les conditions actuelles ''' owm = OWM(API, language='fr') ''' Pour avoir les prochains jours ''' fc = owm.daily_forecast('Saint-Gely-du-Fesc') f = fc.get_forecast() #Listes qui recuperent les infos de la semaine self.Week = [] self.Time = [] self.Meteo = [] self.Wind = [] self.Hum = [] self.TempMax = [] self.TempMin = [] self.Temp2 = [] self.Rain = [] self.Sunrise = [] self.Sunset = [] for w in f: print "TIME : " + str(w.get_reference_time(timeformat='iso')) print self.Time print self.Week print " meteo : " + str(w.get_status()) + " (img = " + str( w.get_weather_icon_name()) + ")" print " rain : " + str(w.get_rain()) print " wind : " + str(w.get_wind()) print " hum : " + str(w.get_humidity()) print " temp : " + str(w.get_temperature(unit='celsius')) print " sunrise: " + str(w.get_sunrise_time('iso')[11:16]) print " sunset: " + str(w.get_sunset_time('iso')[11:16]) #Quand il y a un "if" avec un '== "." ', cela veut dire qu l'on ne veut que la partie entiere de la donnee (on enleve les decimales) self.Day = (str(w.get_reference_time(timeformat='iso'))[8:10]) self.Month = (str(w.get_reference_time(timeformat='iso'))[5:7]) self.Year = (str(w.get_reference_time(timeformat='iso'))[0:4]) self.Time.append(self.Day + "-" + self.Month + "-" + self.Year) #Date "a la francaise" self.Week.append(self.Day + "/" + self.Month) #Date "reduite" pour cases du bas self.Meteo.append(str(w.get_weather_icon_name())) #Si aucune info concernant la proba de pluie n'est donnee alors il y aura 0% de proba de pluie try: if str(w.get_rain()['all'])[2:3] == ".": self.Rain.append(str(w.get_rain()['all'])[0:2]) else: self.Rain.append(str(w.get_rain()['all'])) except: self.Rain.append("0") if str(w.get_wind()['speed'] * 3.6)[2:3] == ".": self.Wind.append(str(w.get_wind()['speed'] * 3.6)[0:2]) else: self.Wind.append(str(w.get_wind()['speed'] * 3.6)[0:3]) self.Hum.append(str(w.get_humidity())) if str((w.get_temperature(unit='celsius')['max']))[1:2] == ".": self.TempMax.append( str((w.get_temperature(unit='celsius')['max']))[0:1]) else: self.TempMax.append( str((w.get_temperature(unit='celsius')['max']))[0:2]) if str((w.get_temperature(unit='celsius')['min']))[1:2] == ".": self.TempMin.append( str((w.get_temperature(unit='celsius')['min']))[0:1]) else: self.TempMin.append( str((w.get_temperature(unit='celsius')['min']))[0:2]) if str((w.get_temperature(unit='celsius')['day']))[1:2] == ".": self.Temp2.append( str((w.get_temperature(unit='celsius')['day']))[0:1]) else: self.Temp2.append( str((w.get_temperature(unit='celsius')['day']))[0:2]) self.Sunrise.append(str(w.get_sunrise_time('iso')[11:16])) self.Sunset.append(str(w.get_sunset_time('iso')[11:16])) self.DailyWeather = daily_weather( self.Meteo, self.TempMax, self.TempMin, self.Hum, self.Rain, self.Wind, self.Sunrise, self.Sunset, self.Time, self.Week, self.Temp2) #Temperatures des cases du bas (moyenne du jour)
parser = argparse.ArgumentParser() parser.add_argument('--owmkey', help='API key to http://openweathermap.org/', required=True) parser.add_argument('--city', help='City', default='Wroclaw, PL') args = parser.parse_args() owm = OWM(language='en', API_key=args.owmkey, version='2.5') icons = [] icons_parse = [] highs = [] lows = [] dates = [] forecast = owm.daily_forecast(args.city, limit=4).get_forecast() for weather in forecast: # Parse icons icons.append(weather.get_weather_code()) # Parse temperature highs highs.append(round(weather.get_temperature(unit='celsius')['max'], 1)) # Parse temperature lows lows.append(round(weather.get_temperature(unit='celsius')['min'], 1)) # Parse dates dates.append(weather.get_reference_time('iso')[:-12]) # Parse date day_one = datetime.datetime.strptime(str(dates[0]), '%Y-%m-%d') # Change icons from OWM format to the format the svg wants them in. This is # really ugly code. I couldn't think of a better way to do it though, so for
visibility_distance = obs._weather._visibility_distance humiditiy = obs._weather._humidity wind = obs._weather._wind pressure = obs._weather._pressure # make a three hour forecast object fc and extract fc= owm.three_hours_forecast("London") number_of_available_observations = fc._forecast.__len__() for i in range(number_of_available_observations-1, -1, -1): three_hour_fc = fc._forecast._weathers.pop(i) print(three_hour_fc._reference_time, three_hour_fc._status, three_hour_fc._temperature, three_hour_fc._weather_icon_name) # make a daily forcast object fd print("\nDaily forecasts") fd = owm.daily_forecast(name="London", limit = 7) number_of_available_observations = fd._forecast.__len__() print(number_of_available_observations) for i in range(number_of_available_observations-1, -1, -1): three_hour_fd = fd._forecast._weathers.pop(i) print(three_hour_fd._reference_time, three_hour_fd._status, three_hour_fd._temperature, three_hour_fd._weather_icon_name)
#This class is used to test PYOWM functionalities from pyowm import OWM owm = OWM('538cea50e439653ca98c8a8c1f5b6f8b') obs = owm.weather_at_place('London,uk') w = obs.get_weather() #get current weather data print("Get temperature: ", w.get_temperature()) #get forecast information fc = owm.daily_forecast('San Jose, us') print("Have sun?: ", fc.will_have_sun()) print("Have rain?: ", fc.will_have_rain()) print("Have fog?: ", fc.will_have_fog()) print("Have clouds? ", fc.will_have_clouds())