def __display_forecast(self): forecastobject = self.weatherObj.getForecast() for i in range(len(forecastobject)): temprange = pygame.font.SysFont(self._font, int(self._ymax * 0.05), bold=1) rendertemprange = temprange.render( str(int(pytemperature.k2f(float(forecastobject[i]["high"])))) + "/" + str(int(pytemperature.k2f(float(forecastobject[i]["low"])))), True, self._font_color) displaytime = datetime.datetime.fromtimestamp( float(forecastobject[i]["date"])).strftime('%a') dayofweek = pygame.font.SysFont(self._font, int(self._ymax * 0.05), bold=1) renderdayofweek = dayofweek.render(displaytime, True, self._font_color) iconref = str(forecastobject[i]["icon"]) if iconref in settings.icon_map: icon = pygame.image.load_extended(settings.ICON_BASE_DIR + settings.icon_map[iconref]) self._screen.blit(icon, ((self._xmax * 0.4) + (self._xmax * 0.2) * (i) + 50, int(self._ymax - 130))) self._screen.blit(rendertemprange, ((self._xmax * 0.4) + (self._xmax * 0.2) * (i) + 50, int(self._ymax - 50))) self._screen.blit(renderdayofweek, ((self._xmax * 0.4) + (self._xmax * 0.2) * (i) + 50, int(self._ymax - 180)))
def get_weather(): log_call() url = "http://api.openweathermap.org/data/2.5/weather?lat=32.871&lon=-117.202&appid=3294e2836901a1399a3c094dc825a1b2" response = requests.get(url) url2 = 'http://api.openweathermap.org/data/2.5/uvi?lat=32.871&lon=-117.202&appid=3294e2836901a1399a3c094dc825a1b2' response2 = requests.get(url2) weather_get = json.loads(response.text) weather_get2 = json.loads(response2.text) headers = {'x-access-token': '446c72a5f4b93323b21616dc08290411'} a = requests.get('https://api.openuv.io/api/v1/uv?lat=32.871&lng=-117.202', headers=headers) a_get = json.loads(a.text) weather_type = weather_get['weather'][0]['description'] temperature = str(round(pytemperature.k2f(weather_get['main']['temp']), 1)) + "°F" temp_feels_like = str( round(pytemperature.k2f(weather_get['main']['feels_like']), 1)) + "°F" cloud_percentage = str(weather_get['clouds']['all']) + "%" wind = str(round(weather_get['wind']['speed'] * 2.23694, 1)) + 'MPH / ' + str(weather_get['wind']['deg']) + "°" humidity = str(weather_get['main']['humidity']) + "%" uv = str(int(round(weather_get2['value'], 0))) weather_stats = [ weather_type, temperature, temp_feels_like, cloud_percentage, wind, humidity, uv ] return weather_stats
def create_dict(self, d): self.d = d #current temp temp = d[1]["main"]["temp"] fahrenheit = pytemperature.k2f(temp) #tonight temp temp_night = d[0]['list'][2]["main"]["temp_min"] fahrenheit2 = pytemperature.k2f(temp_night) #tomorrow temp tomorrow = d[0]['list'][5]["main"]["temp_max"] fahrenheit3 = pytemperature.k2f(tomorrow) #current humidity humidity = d[0]["list"][1]['main']['humidity'] #location # location=d[] #current cloud cover = d[1]["weather"][0]["description"] #current id ids = d[1]["weather"][0]['id'] #tonight id ids2 = d[0]['list'][2]["weather"][0]['id'] #tomorrow id ids3 = d[0]['list'][5]["weather"][0]['id'] #current wind wind = d[1]["wind"]["speed"] mph = round(convertms2mph(wind), 2) #current amORpm time = amORpm() dict_main = { "current": fahrenheit, "tonight": fahrenheit2, "wind": mph, "humidity": humidity, "description": cover, "id": ids, "tomo_id": ids3, "tonight_id": ids2, "tomorrow": fahrenheit3, "time": time } return dict_main
def citystuff(): import requests import pytemperature API_key = "f2a99365b7628b1ea22823fbcda4dd84" base_url = "http://api.openweathermap.org/data/2.5/weather?" city_name = input("Enter City Name : ") Final_url = base_url + "appid=" + API_key + "&q=" + city_name try: response = requests.get(Final_url) weather_data = requests.get(Final_url).json() response.raise_for_status() print('Successful Process with', response.status_code) except requests.exceptions.HTTPError as e: # print (e.response.text) print("404-City Not Found") # city is not found if response.status_code != 404: # store the value of "main" # key in variable y # JSON data works just similar to python dictionary and you can access the value using []. # Accessing Temperature, temperature resides in main and its key is temp temp = weather_data['main']['temp'] # Accessing wind speed, it resides in wind and its key is speed wind_speed = weather_data['wind']['speed'] # Accessing Description, it resides in weather and its key is description description = weather_data['weather'][0]['description'] # Accessing Latitude, it resides in coord and its key is lat low_temp = weather_data['main']['temp_min'] # Accessing Longitude, it resides in coord and its key is lon high_temp = weather_data['main']['temp_max'] # Printing Data #print(response.status_code) # To print http response code print('Temperature : ', pytemperature.k2f(temp)) # Kelvin to Fahrenheit print('Low Temp: ', pytemperature.k2f(low_temp)) print('High Temp : ', pytemperature.k2f(high_temp)) print('Wind Speed : ', wind_speed) print('Description : ', description) else: print("Please try again ")
def getWeatherSummary(city): key = sample_config.api_key() api_address = "http://api.openweathermap.org/data/2.5/weather?" + "appid=" + key + "&q=" city = city try: url = api_address + city except TypeError: #print "Error: Not a string" return "ERROR: Not a string" #return #below is my error checking for the API. try: response = requests.get(url).json() except requests.exceptions.HTTPError as errh: return "ERROR: An Http Error occurred:" + repr(errh) except requests.exceptions.ConnectionError as errc: return "ERROR: An Error Connecting to the API occurred:" + repr(errc) except requests.exceptions.Timeout as errt: return "ERROR: A Timeout Error occurred:" + repr(errt) except requests.exceptions.RequestException as err: return "ERROR: An Unknown Error occurred" + repr(err) try: data = response['main'] except KeyError: return "ERROR: City not found, please try again" except NameError: return "ERROR:: Not a string" try: formatted_data = response['weather'][0]['description'] except KeyError: return "ERROR: City not found, please try again" except NameError: return "ERROR:: Not a string" temp = data['temp'] temp = pytemperature.k2f(temp) # Kelvin to Fahrenheit humidity = data['humidity'] humidity = humidity #humidity = feels_like = data['feels_like'] feels_like = pytemperature.k2f(feels_like) # Kelvin to Fahrenheit summary = [{ 'Description': formatted_data, 'Outside Temperature': temp, 'Humidity': humidity, 'Feels like': feels_like }] return summary
def citysearch(): import requests import pytemperature #get URL for API call API_key = "f2a99365b7628b1ea22823fbcda4dd84" base_url = "http://api.openweathermap.org/data/2.5/weather?" city_name = input("Enter City Name: ") print("\n") #perform API call and give status message depending if the entry is successful or not Final_url = base_url + "appid=" + API_key + "&q=" + city_name try: response = requests.get(Final_url) weather_data = requests.get(Final_url).json() response.raise_for_status() print('Successful City Name Search! (code =',response.status_code,')' ) except requests.exceptions.HTTPError as e: # print (e.response.text) print("404-City Not Found") #run process if City is found if response.status_code != 404: # Accessing weather info like python dictionary in JSON using [] to call the value temp = weather_data['main']['temp'] # pulling in wind speed, comes from wind section of API call wind_speed = weather_data['wind']['speed'] # pulling in description of weather that comes from weather section of API call description = weather_data['weather'][0]['description'] # pulling in low temp from main section of API call low_temp = weather_data['main']['temp_min'] # pulling in high temp from main section of API call high_temp = weather_data['main']['temp_max'] # Printing Data print("\n") print('Temperature: ',pytemperature.k2f(temp),'degrees') # Kelvin to Fahrenheit print('Low Temp: ',pytemperature.k2f(low_temp),'degrees') print('High Temp: ',pytemperature.k2f(high_temp),'degrees') print('Wind Speed: ',wind_speed,'mph') print('Current Description:',description) #Ask user to reinput request if they enter an invalid city name else: print("Please try again with valid input. ")
def relevantData(zipcode): locationData = fetch.locationData(zipcode) weatherData = {} weatherData["cityName"] = locationData["name"] weatherData["windSpeed"] = locationData["wind"]["speed"] weatherData["currentTemp"] = temp.k2f(locationData["main"]["temp"]) weatherData["maxTemp"] = temp.k2f(locationData["main"]["temp_max"]) weatherData["minTemp"] = temp.k2f(locationData["main"]["temp_min"]) # print(weatherData) return weatherData
def weather(): """ This function will retrive weather data from openweathermap.""" if request.method == "POST": city = request.form["city"] else: city = "nashville" api = "d450efe05541dcf4285ee570f64f3b15" list_of_data = requests.get( "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + api).json() data = { "country_code": str(list_of_data["sys"]["country"]), "name": list_of_data["name"], "lat": list_of_data["coord"]["lat"], "lon": list_of_data["coord"]["lon"], "temp_k": list_of_data["main"]["temp"], "temp_f": pytemperature.k2f(list_of_data["main"]["temp"]), "temp_c": pytemperature.k2c(list_of_data["main"]["temp"]), "pressure": str(list_of_data["main"]["pressure"]), "humidity": str(list_of_data["main"]["humidity"]), } print(data) return render_template("index.html", data=data)
def __display_outdoortemp(self): tempK = self.weatherObj.getCurrentWeather() tempF = int(pytemperature.k2f(float(tempK))) font = pygame.font.SysFont(self._font, int(self._ymax * (0.5 - 0.15) * 0.9), bold=1) temp = font.render(str(tempF), True, self._font_color) (tx, ty) = temp.get_size() ffont = pygame.font.SysFont(self._font, int(self._ymax * (0.5 - 0.15) * 0.5), bold=1) ftext = ffont.render(chr(0x2109), True, self._font_color) (ftx, fty) = ftext.get_size() text = pygame.font.SysFont(self._font, int(self._ymax * 0.07), bold=1) rendertext = text.render("Outdoor", True, self._font_color) (rtx, rty) = rendertext.get_size() self._screen.blit(rendertext, (self._borders[0] + (self._xmax * 0.16 - (int(rtx / 2))), int(self._ymax - ty - 30))) self._screen.blit(temp, (self._borders[0] + 30, int(self._ymax - ty - 10))) self._screen.blit( ftext, (self._borders[0] + 20 + tx + 15, int(self._ymax - ty)))
async def get_weather(ctx, city, country): """ sends the weather for city, country. also sends an icon of the weather. """ city = city.lower().strip().title() country = country.lower().strip().title() owm = pyowm.OWM('5949da28441858d0fcb6070f3cbf6836') try: weather_json = json.loads( owm.weather_at_place('{},{}'.format(city, country)).to_JSON())['Weather'] except: await ctx.send('{}, {}'.format(city, country).title() + ' not found!') return url = 'http://openweathermap.org/img/w/' icon_file = url + weather_json['weather_icon_name'] + '.png' icon = urlopen(icon_file) with open('icon.png', 'wb') as f: shutil.copyfileobj(icon, f) temp = weather_json['temperature']['temp'] output = 'Weather for {}, {}:\n'.format(city, country) output += 'status: ' + weather_json['detailed_status'] + '\n' output += 'cloud %: ' + repr(weather_json['clouds']) + '\n' output += ('temperature: Farenheit: %s, Celsius: %s' % (round(k2f(int(temp)), 1), round(k2c(int(temp)), 1))) + '\n' await ctx.send(output, file=discord.File('icon.png'))
def get_local_weather(): weather = [] r = requests.get( 'http://api.openweathermap.org/data/2.5/weather?zip=46204&APPID=c5dbe8cac6dbbc3c486534852fb410c7' ) data = r.json() description = data['weather'][0]['description'] low_temp = data['main']['temp_min'] high_temp = data['main']['temp_max'] description high = pytemperature.k2f(high_temp) low = pytemperature.k2f(low_temp) weather.append(description) weather.append(high) weather.append(low) return weather
def city_forecast(city): print(city) weatherApiKey = os.getenv('WEATHER_API_KEY') response = requests.get( "https://community-open-weather-map.p.rapidapi.com/weather?q="+city, headers={ "X-RapidAPI-Host": "community-open-weather-map.p.rapidapi.com", "X-RapidAPI-Key": weatherApiKey }, ) weatherDict = response.json() print(weatherDict) weatherData = {} weatherData['desc'] = weatherDict['weather'][0]['description'] weatherData['currentTemp'] = pytemperature.k2f(weatherDict['main']['temp']) weatherData['MinTemp']= pytemperature.k2f(weatherDict['main']['temp_min']) weatherData['MaxTemp']=pytemperature.k2f(weatherDict['main']['temp_max']) print(weatherData) return weatherData
def hello(): time = datetime.now().strftime('%H:%M') #times date = datetime.now().strftime('%m - %d') #times with open('soccerPost.txt') as f: content = [line.decode('utf-8').strip() for line in f.readlines()] #get txt file headlines soccer with open('wnPost.txt') as f1: content1 = [line.decode('utf-8').strip() for line in f1.readlines() ] #get txt file healines world news request = ( 'http://api.openweathermap.org/data/2.5/weather?q=Chicago&appid=9b56b06ab4c7f06821ccf55e3e10fce5' ) response = urllib2.urlopen(request) str_response = response.read().decode('utf-8') obj = json.loads(str_response) # TempLow Kelvin tempLow_kelvin = obj['main']['temp_min'] tempHigh_kelvin = obj['main']['temp_max'] tempCur_kelvin = obj['main']['temp'] # TempHigh Farenheit tempLow_faren = pytemperature.k2f(tempLow_kelvin) tempHigh_faren = pytemperature.k2f(tempHigh_kelvin) tempCur_faren = pytemperature.k2f(tempCur_kelvin) # Weather Description descrip = obj['weather'].pop() descrip = descrip.values()[3] return render_template("index.html", time=time, date=date, content=content, content1=content1, tempHigh_faren=tempHigh_faren, tempLow_faren=tempLow_faren, tempCur_faren=tempCur_faren, descrip=descrip)
def get(self, request, *args, **kwargs): # Lista unaprijed određenih gradova, kao i favorita feat_cities = sidelist(request) favourite_cities = user_views.favourites(request) fav = False search_word = self.kwargs['name'] try: data = get_weather(self.kwargs['name']) except: error = True return Response({'error':error, 'city':search_word, 'favourite_cities':favourite_cities, 'feat_cities':feat_cities}, template_name='wetcity.html') # Pretvorba temperature - pytemperature data['main']['temp'] = pyt.k2f(data['main']['temp']) data['main']['feels_like'] = pyt.k2f(data['main']['feels_like']) # utvrđivanje je li grad favorit if favourite_cities: for favor in favourite_cities: if data['id'] == favor.api_id: fav = True return Response({'data': data, 'city':search_word, 'favourite_cities':favourite_cities, 'fav':fav, 'feat_cities':feat_cities}, template_name='wetcity.html')
def forecasting(user_data): forecast = [] body = user_data # filtering the forecast data got from the api call # 40 here implies every 3 hours data for 5 days so # 24 / 3 x 5 for i in range(40): # make a temporary dictionary # which stores all the important values as dictionary elements temp = {} curr_dir = body["list"][i] temp["temp"] = k2f(curr_dir["main"]["temp"]) temp["temp_min"] = k2f(curr_dir["main"]["temp_min"]) temp["temp_max"] = k2f(curr_dir["main"]["temp_max"]) temp["humidity"] = curr_dir["main"]["humidity"] temp["weather"] = curr_dir["weather"][0]["main"] temp["wind_speed"] = curr_dir["wind"]["speed"] temp["date_time"] = curr_dir["dt_txt"] forecast.append(temp) # returning complete list of forecast which has all elements as dictionary return forecast
def get_weather(): import requests, json import pytemperature # Enter your API key here open_weather_api_key = "2b8247bdc1ee06ed27fbc6c20d43a209" # base_url variable to store url base_url = "http://api.openweathermap.org/data/2.5/weather?" # Give city name city_name = 'Fargo' # complete_url variable to store # complete url address complete_url = base_url + "appid=" + open_weather_api_key + "&q=" + city_name # get method of requests module # return response object response = requests.get(complete_url) # json method of response object # convert json format data into # python format data website_response = response.json() # Now website_response contains list of nested dictionaries # Check the value of "cod" key is equal to # "404", means city is found otherwise, # city is not found if website_response["cod"] != "404": # Primary Fields main_formatted = website_response["main"] wind_formatted = website_response["wind"] weather_formatted = website_response["weather"] # Get the informatino kelvin_temperature = main_formatted["temp"] current_temperature = pytemperature.k2f(kelvin_temperature) current_humidity = main_formatted["humidity"] current_windspeed = wind_formatted["speed"] current_wind_direction = degToCompass(wind_formatted["deg"]) # current_wind_gusts = wind_formatted["gust"] current_weather = weather_formatted[0][ "description"] # zeroeth index has description current_pressure = main_formatted["pressure"] return current_temperature, current_humidity, current_windspeed, current_wind_direction, current_weather, current_pressure else: # Some sort of error occurred. Return errors. return "Error!", "Error!", "Error!", "Error!", "Error!", "Error!", "Error!"
def assess_weather(lat, long, api_key): # base_url variable to store url base_url = "http://api.openweathermap.org/data/2.5/weather?" # complete_url variable to store # complete url address #complete_url = base_url + "appid=" + api_key + "&q=" + city_name complete_url = base_url + "lat=" + lat + '&lon=' + long + "&appid=" + api_key # get method of requests module # return response object response = requests.get(complete_url) # json method of response object # convert json format data into # python format data x = response.json() # Now x contains list of nested dictionaries # Check the value of "cod" key is equal to # "404", means city is found otherwise, # city is not found if x["cod"] != "404": # store the value of "main" # key in variable y y = x["main"] # store the value corresponding # to the "temp" key of y current_temperature = pytemperature.k2f(y["temp_max"]) # store the value corresponding # to the "pressure" key of y current_pressure = y["pressure"] # store the value corresponding # to the "humidity" key of y current_humidiy = y["humidity"] # store the value of "weather" # key in variable z z = x["weather"] # store the value corresponding # to the "description" key at # the 0th index of z weather_description = z[0]["description"] return current_temperature
def assign_json_values_to_dict(fresh_json): """ fresh_json: newly received JSON from API call initialize dictionary to return to main() assign specific items from fresh_json to keys in dict return dict """ weather_info = {'description': '', 'temp': 0.0, 'pressure': 0.0, 'humidity': 0, 'temp_min': 0.0, 'temp_max': 0.0} weather_info['description'] = fresh_json['weather'][0]['description'] # key, list, value weather_info['temp'] = pytemperature.k2f(fresh_json['main']['temp']) # conv. kelvin to fahren weather_info['pressure'] = fresh_json['main']['pressure'] / 3386 * 100 # ^^^ divide hpa (pascal) by 3386 to convert to inHg (inches of mercury) weather_info['humidity'] = fresh_json['main']['humidity'] weather_info['temp_min'] = pytemperature.k2f(fresh_json['main']['temp_min']) weather_info['temp_max'] = pytemperature.k2f(fresh_json['main']['temp_max']) return weather_info
def get_weather_data(self): ''' Requests data from the OpenWeather API and extracts the necessary information into a tuple''' r = requests.get(self.url3, headers=self.headers) request_dict = json.loads(r.text) # And then load it into a dictionary weather = request_dict["weather"][0]["main"].lower() weather_id = 0 temperature = request_dict["main"]["temp"] dateTimeObj = datetime.datetime.now() current_time_stamp = str(dateTimeObj) if (weather == "drizzle"): weather_id = 1 elif (weather == "rain"): weather_id = 2 elif (weather == "snow"): weather_id = 3 elif (weather == "clouds"): weather_id = 4 elif (weather == "thunderstorm"): weather_id = 5 elif (weather == "mist"): weather_id = 6 elif (weather == "smoke"): weather_id = 7 elif (weather == "haze"): weather_id = 8 elif (weather == "dust"): weather_id = 9 elif (weather == "fog"): weather_id = 10 elif (weather == "sand"): weather_id = 11 elif (weather == "ash"): weather_id = 12 elif (weather == "squalls"): weather_id = 13 elif (weather == "tornado"): weather_id = 14 new_temp = pytemperature.k2f(temperature) new_temp = int(round(new_temp)) main_weather_tup = (current_time_stamp, new_temp, weather_id, weather) return main_weather_tup
def convertTemperature(input_numerical_value, input_uom, target_uom): outputTemp = 0.0 if(input_uom == 'Kelvin'): if(target_uom == 'Celsius'): outputTemp = pytemperature.k2c(float(input_numerical_value)) elif(target_uom == 'Fahrenheit'): outputTemp = pytemperature.k2f(float(input_numerical_value)) if(input_uom == 'Celsius'): if(target_uom == 'Kelvin'): outputTemp = pytemperature.c2k(float(input_numerical_value)) elif(target_uom == 'Fahrenheit'): outputTemp = pytemperature.c2f(float(input_numerical_value)) if(input_uom == 'Fahrenheit'): if(target_uom == 'Kelvin'): outputTemp = pytemperature.c2k(float(input_numerical_value)) elif(target_uom == 'Celsius'): outputTemp = pytemperature.c2f(float(input_numerical_value)) return outputTemp
def new_pg(request): x = request.GET['city'] y = request.GET['country'] countries = {} for country in pycountry.countries: countries[country.name] = country.alpha_2 code = countries.get(y, 'Unknown code') cc = code.lower() api_address = 'http://api.openweathermap.org/data/2.5/forecast?q={x},{code}&appid=0c42f7f6b53b244c78a418f4f181282a'.format( x=x, code=cc) print(api_address) json_data = requests.get(api_address).json() li = json_data['list'] data = pd.DataFrame(columns=['date_time', 'Temperature']) for i in li: dt = i['dt_txt'] date = dateutil.parser.parse(dt).date() time = dateutil.parser.parse(dt).time() tem = i['main']['temp'] temp = pytemperature.k2f(tem) desc = i['weather'][0]['description'] print("Date Time: ", dt) print("Date: ", date) print("Time: ", time) print("Temperature: ", temp) print("Description: ", desc) print() print() data = data.append({ 'date_time': dt, 'Temperature': temp }, ignore_index=True) # print(json_data.keys) # print((json_normalize(json_data)).columns) print(data) data.to_csv('file1.csv') temp = data['Temperature'] date = data['date_time'] pp.plot(date, temp) pp.xticks(date, date, rotation='vertical') data = pp.show() return render(request, 'plot1.html')
def zipstuff(): import requests import pytemperature API_key = "f2a99365b7628b1ea22823fbcda4dd84" base_url = "http://api.openweathermap.org/data/2.5/weather?" zip_code = input("Enter zip code : ") Final_url = base_url + "appid=" + API_key + "&q=" + zip_code try: response = requests.get(Final_url) weather_data = requests.get(Final_url).json() response.raise_for_status() print('Successful Process with', response.status_code) except requests.exceptions.HTTPError as e: print(e.response.text) # JSON data works just similar to python dictionary and you can access the value using []. # Accessing Temperature, temperature resides in main and its key is temp temp = weather_data['main']['temp'] # Accessing wind speed, it resides in wind and its key is speed wind_speed = weather_data['wind']['speed'] # Accessing Description, it resides in weather and its key is description description = weather_data['weather'][0]['description'] # Accessing Latitude, it resides in coord and its key is lat latitude = weather_data['coord']['lat'] # Accessing Longitude, it resides in coord and its key is lon longitude = weather_data['coord']['lon'] # Printing Data #print(response.status_code) # To print http response code print('Temperature : ', pytemperature.k2f(temp)) # Kelvin to Fahrenheit print('Wind Speed : ', wind_speed) print('Description : ', description) print('Latitude : ', latitude) print('Longitude : ', longitude)
def update_channels_ui(self): for ch, ch_ui in self.channels.items(): # get ui elements ch_ui = self.channels[ch] lbl_channel = ch_ui['lbl_channel'] lbl_unit = ch_ui['lbl_unit'] sb_temp = ch_ui['sb_temp'] # update ui elements lbl_channel.setText(self.inst.channel_names[ch]) unit = self.inst.units[ch] lbl_unit.setText(unit) # hide and show set point controls if self.inst.get_channel_loop(ch) is None: sb_temp.hide() else: sb_temp.show() # temperature mins and maxes max_temp = self.inst.channel_max_temperature(ch) min_temp = 0 if unit == 'C': min_temp = pytemp.k2c(min_temp) elif unit == 'F': min_temp = pytemp.k2f(min_temp) sb_temp.setMinimum(min_temp) if max_temp is not None: sb_temp.setMaximum(max_temp) set_pt = self.inst.set_point(ch) if set_pt is not None: sb_temp.setValue(set_pt)
def getRequest(self): self.response = requests.get(self.complete_url) self.weather = self.response.json() # print(self.weather) if self.weather['cod'] != '404': main = self.weather['main'] hummidity = main['humidity'] kelvin = main['temp'] temperature = pytemperature.k2f(kelvin) temp = str(temperature) w = self.weather['wind'] windSpeed = w['speed'] wind = str(windSpeed) city = self.weather['name'] description = self.weather['weather'][0]['description'] report = 'The temperature in ' + city + ' is ' + temp + ' with a windspeed of ' + wind + ', ' + description + ' likely.' print(report)
def get_weather(api_key, city, country): erqrew url = f"http://api.openweathermap.org/data/2.5/weather?q={city},{country}&appid={api_key}" res = requests.get(url) result = res.json() y = result['main'] current_temperature = y["temp"] current_pressure = y["pressure"] current_humidity = y["humidity"] z = result["weather"] weather_description = z[0]["description"] print(" Temperature (in Kelvin) = " + str(current_temperature) + "\n Temperature (in Celsius) = " + str(pytemperature.k2c(current_temperature)) + "\n Temperature (in Farenheit) = " + str(pytemperature.k2f(current_temperature)) + "\n atmospheric pressure (in hPa unit) = " + str(current_pressure) + "\n humidity (in percentage) = " + str(current_humidity) + "\n description = " + str(weather_description))
try: location_dict['points of interest'].append(POI_results[i]) except IndexError: location_dict['points of interest'].append( "No Point of Interest #" + str(i + 1) + " for " + city_name) print("No Point of Interest #" + str(i + 1) + " for " + city_name) # print(city_name + " access successful") -> use this for debugging complete_url = weather_url + "lat=" + str(lat) + "&lon=" + str( lon) + "&appid=" + API_KEY weather_response = requests.get(complete_url).json() # print(city_name) -> use this for debugging current_temp = weather_response['current']['temp'] location_dict['weather']['current_temperature'] = str( pytemp.k2f(current_temp)) + " " + degree_sign + "F" for day in weather_response['daily']: day_temp = day['temp']['day'] location_dict['weather']['week_forecast'].append( str(pytemp.k2f(day_temp)) + " " + degree_sign + "F") # print(city_name + " access successful") -> use this for debugging db_array.append(location_dict) # Use the following to create index for the first time, then comment out: # locations.create_index([ # ('name', 'text') # ], # name="search_index" # )
city = input('What city?: \n') temp = input("Which temp format? C or F?: \n").lower() package = { 'APPID': "8b447aaba14ad1e178b186031642d0de", 'q': city } r = requests.post('http://api.openweathermap.org/data/2.5/weather', params=package) data = r.json() print('Condition: ' + data['weather'][0]['main']) if temp == 'c': print('Temp: ' + str(pytemperature.k2c(int(data['main']['temp'])))) elif temp == 'f': print('Temp: ' + str(pytemperature.k2f(int(data['main']['temp'])))) if data['wind']['deg'] >= 0 and data['wind']['deg'] <= 25: print('Wind Direction: North') elif data['wind']['deg'] > 25 and data['wind']['deg'] <= 68: print('Wind Direction: Northeast') elif data['wind']['deg'] > 68 and data['wind']['deg'] <= 110: print('Wind Direction: East') elif data['wind']['deg'] > 110 and data['wind']['deg'] <= 150: print('Wind Direction: Southeast') elif data['wind']['deg'] > 150 and data['wind']['deg'] <= 205: print('Wind Direction: South') elif data['wind']['deg'] > 205 and data['wind']['deg'] <= 245: print('Wind Direction: Southwest') elif data['wind']['deg'] > 245 and data['wind']['deg'] <= 295: print('Wind Direction: West')
weather_data = requests.get(Final_url).json() response.raise_for_status() print('Successful Process with', response.status_code) except requests.exceptions.HTTPError as e: print(e.response.text) # JSON data works just similar to python dictionary and you can access the value using []. # Accessing Temperature, temperature resides in main and its key is temp temp = weather_data['main']['temp'] # Accessing wind speed, it resides in wind and its key is speed wind_speed = weather_data['wind']['speed'] # Accessing Description, it resides in weather and its key is description description = weather_data['weather'][0]['description'] # Accessing Latitude, it resides in coord and its key is lat latitude = weather_data['coord']['lat'] # Accessing Longitude, it resides in coord and its key is lon longitude = weather_data['coord']['lon'] # Printing Data #print(response.status_code) # To print http response code print('Temperature : ', pytemperature.k2f(temp)) # Kelvin to Fahrenheit print('Wind Speed : ', wind_speed) print('Description : ', description) print('Latitude : ', latitude) print('Longitude : ', longitude)
weather_client = weather.Client() while True: zipcode = input('Zipcode? ').strip() if len(zipcode) == 0: break forecast = weather_client.get_forecast(zipcode) # OWM API appears inconsistent with strings/integers in this field if str(forecast['cod']) != '200': print(forecast['message']) continue print('Weather for {zipcode} ({city}):'.format(zipcode=zipcode, city=forecast['name'])) temp = pytemperature.k2f(forecast['main']['temp']) print(' {temp}° F'.format(temp=temp)) for item in forecast['weather']: print(' {main}'.format(**item)) now = time.time() for event in ['sunrise', 'sunset']: if now < forecast['sys'][event]: human_offset = arrow.Arrow.fromtimestamp( forecast['sys'][event]).humanize() print(' {event} {human_offset}'.format( event=event.capitalize(), human_offset=human_offset)) break print('')
def getLow(self): low = self.data['temp_min'] low = str(pytemperature.k2f(low)) + self.m_symbol return low