def get_forecast(lng, lat): """Return weather forecast for the next week""" weekday = datetime.date.today() sf = forecast(mykey, lat, lng) html_str = "" forecast_data = {} with forecast(mykey, lat, lng) as sf: forecast_data["daily_summary"] = sf.daily.summary forecast_data["daily_forecast"] = [] html_str += "7-day WEATHER FORECAST SUMMARY: " + str( sf.daily.summary) + "<br><br>\n" for day in sf.daily: day = dict(day=datetime.date.strftime(weekday, '%a'), sum=day.summary, tempMin=day.temperatureMin, tempMax=day.temperatureMax) html_str += "{day}: {sum} Temp range: {tempMin} - {tempMax}".format( **day) html_str += "<br>\n" weekday += datetime.timedelta(days=1) return html_str
def write_weather_data(dates, hours, apikey, latlon, append_output=False, filepath='../precrime_data/weather_hist.csv'): """Call the Dark Sky API and save the weather data. Parameters ---------- dates : list A list of dates (supporting .year, .month, and .day) to download the weather for hours : list A list of integers representing the hours of each day that we want to get the weather for. The total number of forecasts download is len(dates) * len(hours) apikey : string Dark Sky API key latlon : tuple latlon[0] = latitude, latlon[1] = longitude append_output : boolean, optional, default False If True, will not write a header row and will not overwrite the file filepath : string, optional Where to write the output Returns ------- None """ if append_output: write_header = False file_mode = 'a' else: write_header = True file_mode = 'w' weather_location = [apikey, latlon[0], latlon[1]] with open(filepath, file_mode, newline='') as csvfile: # Create the list of dict fields we'll be including in the file. # Add 'precipType' in case it isn't currently raining while # this script is being run. with forecast(*weather_location) as current_weather: weather_fields = sorted( list( set(['precipType'] + list(current_weather.currently._data.keys())))) writer = csv.DictWriter(csvfile, fieldnames=weather_fields) if write_header: writer.writeheader() for date in dates: for hour in hours: t = dt(date.year, date.month, date.day, hour).isoformat() with forecast(*weather_location, time=t) as local_weather: writer.writerow({ k: v for k, v in local_weather.currently._data.items() })
def home(request) : # boston = 42.3601, -71.0589 boston = 34.005143,-6.823645 weekday = date.today() weekly_weather = {} with forecast('cc3aae97f4aa5697aa47c5624a085e10', *boston) as boston: print(boston.daily.summary) for day in boston.daily: day = dict(day = date.strftime(weekday, '%a'), sum = day.summary, tempMin = int((day.temperatureMin-32) *(5/9)), tempMax = int ((day.temperatureMax-32) *(5/9)) ) print('{day}: {sum} Temp range: {tempMin} - {tempMax}'.format(**day)) weekday += timedelta(days=1) #------------------------# pic = '' summary = ('{sum}'.format(**day).lower()) if 'drizzle' in summary : pic ='rain.png' if 'rain' in summary : pic ='rain.png' if 'cloudy' in summary : pic ='clouds.png' if 'clear' in summary : pic ='sun.png' if 'party cloudy' in summary : pic ='rain.png' if 'drizzle' in summary : pic ='party-cloudy-day.png' hour = datetime.now().hour location = forecast('cc3aae97f4aa5697aa47c5624a085e10',34.005143,-6.823645) i= 0 while hour < 24 : temp = location.hourly[i].temperature if hour > 12 : print('{} pm - {}'.format(hour,temp)) else : print('{} am - {}'.format(hour,temp)) hour += 1 i+=1 return render(request,'home.html',{})
def main(): SAOPAULO = -23.5489, -46.6388 #latitude e longitude de São Paulo RIO = -22.9035, -43.2096 # latitude e longetude do Rio de Janeiro KEY = 'INSERT YOUR API KEY FROM THE DARKSKY WEATHER API' insert_query = """ INSERT INTO weather_forecast (city, minimum_temp, maximum_temp, date) VALUES(%s, %s, %s, %s) """ datasetsp = [] datasetrio = [] weekday = date.today() with forecast(KEY, *SAOPAULO, units='si') as saopaulo: print("Summary for Sao Paulo") print(saopaulo.daily.summary, end='\n---\n') for day in saopaulo.daily: datasetsp.append([ 'sao paulo', day['temperatureMin'], day['temperatureMax'], datetime.utcfromtimestamp(day['time']).strftime('%Y-%m-%d') ]) weekday += timedelta(days=1) print(datasetsp) with forecast(KEY, *RIO, units='si') as rio: print("Summary for Rio de Janeiro") print(rio.daily.summary, end='\n---\n') for day in rio.daily: datasetrio.append([ 'rio de janeiro', day['temperatureMin'], day['temperatureMax'], datetime.utcfromtimestamp(day['time']).strftime('%Y-%m-%d') ]) weekday += timedelta(days=1) print(datasetrio) try: con = psycopg2.connect(user="******", password="******", host="127.0.0.1", database="INSERT_YOUR_DB_NAME") cur = con.cursor() cur.executemany(insert_query, datasetsp) cur.executemany(insert_query, datasetrio) con.commit() con.close() except (Exception): print("Database error!") raise
def future_weather(self,api, lat, lon, hours, time): days = int(hours) // 24 hour = int(hours) % 24 data = [] for i in range(days): t = time.shift(days=+i) t = dt.datetime(t.year,t.month, t.day, 0).isoformat() weather = forecast(api, lat, lon, time=t) data.extend([self.ftoc(hour.temperature) for hour in weather.hourly[:24]]) if hour != 0: t = time.shift(days=+days) t = dt.datetime(t.year,t.month, t.day, 0).isoformat() weather = forecast(api, lat, lon, time=t) data.extend([self.ftoc(hour.temperature) for hour in weather.hourly[:hours]]) return data
def add_head(self): top = QFrame() top.setFrameShape(QFrame.WinPanel) top.setFrameShadow(QFrame.Raised) top.setMaximumHeight(100) top.setStyleSheet("background-color: red;") clk = clock.Clock(parent=top) clk.setFrameShape(QFrame.NoFrame) clk.setStyleSheet("background-color:none; color: white;") clk.move(-75, -75) clk.setMinimumWidth(250) clk.setMinimumHeight(250) next_bus = QLabel(top) next_bus.setFont(QFont("Sans-serif", 42, QFont.Bold)) bus = self.l[0][0] time = self.l[0][1] next_bus.setText("<font color='white'>Next Bus: " + bus + " in " + time + "</font>") next_bus.move(int(self.screen.width() / 2) - 400, 25) weather = QLabel(top) weather.setFont(QFont("Sans-serif", 42, QFont.Bold)) w = forecast('c505a8dedfcf4bc235046f56138a67d9', 51.0253, -114.0499) temp = round(w['currently']['temperature']) weather.setText("<font color='white'>" + str(temp) + "°</font>") weather.move(self.screen.width() - 130, 25) self.layout.addWidget(top)
def show_weather(self): try: city = self.setcity.text() country = self.setcountry.text() location = geocoder.yandex(city + ' ' + country) data = forecast(KEY, location.latlng[0], f'{location.latlng[1]}?lang=ru&units=si') except Exception: answ = QMessageBox.question( self, 'Ошибка', 'Город/страна не найден(а) Попробуете еще раз?') if answ == QMessageBox.No: self.close() else: cc = '' while ', ' not in cc: cc, btn = QInputDialog.getText(self, 'Погода для народа', 'Введите город, страну:') if not btn: self.close() break if btn: cc = cc.split(', ') self.setcity.setText(cc[0]) self.setcountry.setText(cc[1]) self.show_weather() else: options = self.set_options(self.prm) timeper = self.set_timeper(self.tp) weather = Weather(data, options, timeper, self.view) weather.show_widget()
def get_locations_dict(loc_lst): locs_dict = {} for location in loc_lst: locs_dict[location] = forecast(darksky_key, location.lat, location.lng) return locs_dict
def __init__(self, apiKey, codigo): site, self.latitude, self.longitude = locationSiteCoordenate(codigo) if self.latitude != 0 and self.longitude != 0: fcast = forecast(apiKey, self.latitude, self.longitude, units='si') else: fcast = [] if (fcast): main = fcast.currently self.wdb.setMeasure('humidity' ,main.humidity * 100) self.wdb.setMeasure('pressure' ,main.pressure) self.wdb.setMeasure('temperature' ,main.temperature) self.wdb.setMeasure('temperatureApparent',main.apparentTemperature) self.wdb.setMeasure('temperatureDew' ,main.dewPoint) self.wdb.setMeasure('weatherMain' ,main.summary) self.wdb.setMeasure('latitude' ,self.latitude ) self.wdb.setMeasure('longitude' ,self.longitude) self.wdb.setMeasure('windSpeed' ,main.windSpeed * 3.6) self.wdb.setMeasure('windGust' ,main.windGust * 3.6) self.wdb.setMeasure('windDegrees' ,main.windBearing ) self.wdb.setMeasure('rainIntensity' ,main.precipIntensity) self.wdb.setMeasure('rainProbability' ,main.precipProbability * 100) self.wdb.setMeasure('skyUVIndex' ,main.uvIndex) self.wdb.setMeasure('skyClouds' ,main.cloudCover * 100) self.wdb.setMeasure('skyOzone' ,main.ozone) self.wdb.setMeasure('skyVisibility' ,main.visibility ) self.wdb.setMeasureClean()
def main(): try: c = configparser.ConfigParser() c.read( os.path.join(os.path.abspath(os.path.dirname(__file__)), '../frontend/conf', 'settings.ini')) # Setup Nest account n = Nest(c['nest']['nest_username'], c['nest']['nest_password'], c['nest']['nest_sn'], c['nest']['nest_index'], units=c['common']['units']) n.login() n.get_status() ds = forecast(c['darksky']['api_key'], c.getfloat('darksky', 'lat'), c.getfloat('darksky', 'long')) observation = ds['currently'] w = observation # Connect to DB cnx = mysql.connector.connect(user=c['mysql']['mysql_username'], password=c['mysql']['mysql_password'], host=c['mysql']['mysql_hostname'], database=c['mysql']['mysql_database']) d = cnx.cursor() polling(c, n, w, d) cnx.commit() d.close() except Exception: print(sys.exc_info()[1])
def main(): """ Collect all summer dates in a list and iterate through it""" date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)] for summer_day in date_generated: my_date = dt.strptime(str(summer_day), "%Y-%m-%d").isoformat() #api's time arg requires isoformat for city, coordinates in cities.items(): """connect to the api using darkskylib and fetch the highest temperature and humidity index per each day""" with forecast(token, *coordinates, time=my_date) as values: maxTemp = round(((values['daily']['data'][0]['temperatureMax']) - 32) * 5/9, 1) #convert Fahrenheit to Celsius humidity = values['daily'] ['data'] [0] ['humidity'] """ populate database tables with the city names and respective temperatures and humidity indexes per each summer day""" city_query = """ INSERT IGNORE INTO weather.location(city) VALUES (%s)""" cur.execute(city_query, [city]) temperature_query = "('{0}', '{1}',{2}, {3}, '{4}')".format(city, summer_day, maxTemp, humidity, datetime.date.today()) cur.execute ("""INSERT INTO weather.summer_time (city, summer_day, highest_temp, humidity, in_date) VALUES {0} """.format(temperature_query)) conn.commit() conn.close()
def get_forecast(location): coord = geolocate_city(location) key = '1136ef786eb77b372c671b0b22ae1e0f' print(f'Checking weather for {location}') data = [] with darksky.forecast(key, *coord) as geo_data: for hour in range(len(geo_data.hourly) - 38): hourofforecast = datetime.now().hour + hour if datetime.now().hour + \ hour < 24 else datetime.now().hour + hour - 24 hour = dict(time=str(hourofforecast).zfill(2) + ':' + str(datetime.now().minute), summary=geo_data.hourly[hour].summary, temperature=np.round( (geo_data.hourly[hour].temperature - 32) * .5556, 2), prec_int=np.round( geo_data.hourly[hour].precipIntensity, 2), prec_prob=np.round( geo_data.hourly[hour].precipProbability * 100, 0)) hourly_data = 'At {time}: {summary}, {temperature}°C. Rain prob {prec_prob}% ({prec_int} mm)'.format( **hour) data.append(hourly_data) return 'Hello world'
def ReadValue(self): try: weather = forecast(self.key, self.latitude, self.longitude, units=self.units, timeout=1) except Exception as e: logging.warning("DarkSky warning in Readvalue: " + str(e)) return np.nan try: current = weather.currently except TimeoutError: logging.warning("DarkSky warning in Readvalue: TimeoutError") return np.nan try: nearestStormDistance = current.nearestStormDistance except AttributeError: nearestStormDistance = np.nan values = [ time.time() - self.time_offset, current.temperature, current.humidity, current.dewPoint, current.pressure, current.cloudCover, current.uvIndex, current.windSpeed, current.windGust, current.ozone, current.precipIntensity, current.precipProbability, nearestStormDistance, current.visibility, weather.latitude, weather.longitude ] values = [float(v) for v in values] return values
def ten_years_data(self,time): t = [] time = time.split('-') self.curr_year = dt.today().year for i in range(10): t.append(dt(self.curr_year - i,int(time[1]),int(time[2].split('T')[0]))) """ Loop through 10 years and use the ds API to request it all + Add it all to a list of forecast objects """ loc = [] for i in range(10): print("DEBUG {0}".format(t[i])) loc.append(forecast(self.ds_key, self.geoLoc['lat'], self.geoLoc['lng'], t[i].strftime('%Y-%m-%d' + 'T12:00:00'))) # Set it equal to the first entries just to populated them high_avg = loc[0]['daily']['data'][0]['temperatureHigh'] low_avg = loc[0]['daily']['data'][0]['temperatureLow'] """ Loop through all the objects and pull the data we want """ for i in range(1,10): high_avg += loc[i]['daily']['data'][0]['temperatureHigh'] low_avg += loc[i]['daily']['data'][0]['temperatureLow'] high_avg = high_avg/10 low_avg = low_avg/10 weather_out = {'high_avg': high_avg, 'low_avg':low_avg} return weather_out
def ping_darksky(time, key): """ Interface to Dark Sky API. Requests data from Boston Airport for a specific time. * Arguments: + time: a datetime object. Denotes the day of the requested record. + key: a character string. Key to interface the Dark Sky API. * Returns: + Dictionary containing: + day: datetime of the observation (in timestamp format). + tempMin: minimum temperature in degrees Fahrenheit at that date. + tempMax: maximum temperature in degrees Fahrenheit at that date. + summary: weather summary of that date. + desc: single word description of weather conditions. """ with forecast(key, *BOSTON, time=time.isoformat()) as boston: fetch = {'day': time, 'tempMin': boston.daily[0].temperatureMin, 'tempMax': boston.daily[0].temperatureMax, 'summary': boston.daily[0].summary, 'desc': boston.daily[0].icon} return fetch
def weather_forecast(weather_location, formatted_address): print(f'\n----- Forecast for {formatted_address}-----\n') weekday = date.today() with forecast(f'{DARKSKY_API_KEY}', *weather_location) as location: print( f'Current Temperature in {formatted_address} is {int(round(location.temperature))}\xb0F' ) print(location.daily.summary, end='\n---\n') right_time, dst_offset = time_zone(weather_location, location.time) print( f'Date/Time in {formatted_address} {convert_time(location.time + right_time + dst_offset)}' ) print('--------') for day in location.daily: day = dict(day=date.strftime(weekday, '%a'), sum=day.summary, tempMin=int(round(day.temperatureMin)), tempMax=int(round(day.temperatureMax))) print('{day}: {sum} Temp range: {tempMin}\xb0F - {tempMax}\xb0F'. format(**day)) weekday += timedelta(days=1)
def ping_darksky(time, key): """ Interface to Dark Sky API. Requests data from Boston Airport for a specific time. * Arguments: + time: a datetime object. Denotes the day of the requested record. + key: a character string. Key to interface the Dark Sky API. * Returns: + Dictionary containing: + day: datetime of the observation (in timestamp format). + tempMin: minimum temperature in degrees Fahrenheit at that date. + tempMax: maximum temperature in degrees Fahrenheit at that date. + summary: weather summary of that date. + desc: single word description of weather conditions. + cloud_cover: float denoting the proportion of the skies surface that is obscured by clouds """ boston = forecast(key, *BOSTON, time=time.isoformat()) fetch = { 'day': time, 'tempMin': boston["daily"]["data"][0].get('temperatureMin', np.nan), 'tempMax': boston["daily"]["data"][0].get('temperatureMax', np.nan), 'summary': boston["daily"]["data"][0].get('summary', np.nan), 'desc': boston["daily"]["data"][0].get('icon', np.nan), 'cloudCover': boston["daily"]["data"][0].get('cloudCover', np.nan) } return fetch
def get_weather_forecast(): apikey = '7358efac8f40bf49ceaa4a8c5278bd31' Goleta = [34.4099508, -119.8661304] goleta = forecast(apikey, Goleta[0], Goleta[1]) parameters = [ 'time', 'ozone', 'windGust', 'temperature', 'dewPoint', 'humidity', 'apparentTemperature', 'pressure', 'windSpeed', 'precipProbability', 'visibility', 'cloudCover', 'precipIntensity' ] forecast_data = [] for hour in goleta['hourly']['data']: hourly_data = {} for item in hour: if item in parameters: hourly_data[item] = hour[item] if item == 'temperature' or item == 'apparentTemperature' or item == 'dewPoint': hourly_data[item] = convert_to_celsius(hourly_data[item]) time = datetime.fromtimestamp(int( hour['time'])).strftime('%Y-%m-%d %H:%M:%S') time = datetime.strptime(time, '%Y-%m-%d %H:%M:%S') time = time + timedelta(hours=8, minutes=0) hourly_data['time'] = time hourly_data['hour'] = time.hour forecast_data.append(hourly_data) return forecast_data
def __init__(self, adminId, darkskyKey, lat, longitude): self.adminId = adminId self.approvedUsers = {} self.approvedUsers[self.adminId] = 'ADRIKA' self.darkskyKey = darkskyKey self.weatherTimeLimit = 30.0 self.timePic = 0 self.timeVideo = 0 self.lat = lat self.longitude = longitude self.cityWeatherData = forecast(self.darkskyKey, self.lat, self.longitude) self.enablePic = True self.enableWater = False self.enableLight = True self.enableAdd = True self.enableVideo = True self.picTimeLimit = 2.0 #mins for users (not admin) self.waterTimeLimit = 4.0 #hrs for users (not admin) self.lightTimeLimit = 15.0 #mins for users (not admin) self.weatherTimeLimit = 30.0 #mins for users (not admin) self.vidTimeLimit = 5.0 #mins for users (not admin)
def buildmultidayDF(startday, lastday, coords ): """ Concatène plusieurs jours ensemble startday, lastday: pandas timestamp """ daterange = pd.date_range(start=startday, end=lastday, freq='D', normalize=True) records = [] for day in daterange: day_iso = day.isoformat() print('%i, '%day.day, end='') data = forecast(KEY, *coords, units='si', lang='fr', \ time=day_iso, exclude=EXCLUDE) records_oftheday = data['hourly']['data'] records.extend( records_oftheday ) print( 'done' ) # build DF: allweatherdata = pd.DataFrame.from_records(records, index='time') allweatherdata.drop(COL2DROP, axis=1, inplace=True, errors='ignore') allweatherdata.index = pd.to_datetime(allweatherdata.index, unit='s') allweatherdata['cloudCover'] = allweatherdata['cloudCover'].fillna( 0 ) return allweatherdata
def __init__(self): super(MainWidget, self).__init__() self.get_location() self.weather = forecast(Config.get('darksky', 'api_key'), *self.location, units=Config.get('darksky', 'units'))
def get(self): city_name = request.args.get('city') date = request.args.get('date') # Response if no filter is provided if date is None and city_name is None: return [self.get_weather(city.name)for city in CityModel.query.all()], 200 if city_name is None: return {'message' : 'Please enter a city name to get weather information'}, 400 city = CityModel.find_by_name(city_name.lower()) # Check if provided city exists in the database or not if city: # If city exists check if date is provided or not if date: input_date = parse(date, parserinfo(dayfirst = True)).replace(hour = 0, minute = 0, second = 0, microsecond = 0) # Check if weather information for a particular date is available or not weather_obj = WeatherModel.find_by_date(city.name, input_date) if weather_obj: return weather_obj.json(), 200 # If absent, fetch the data for the city from the API else: new_forecast = forecast(darksky_key, city.latitude, city.longitude, time = input_date.isoformat()) return {'summary' : new_forecast.summary, 'temperature' : new_forecast.temperature, 'humidity' : new_forecast.humidity}, 200 else: return self.get_weather(city.name), 200 return {'message' : 'Requested city is not present in the database'}, 400
def getWeather(city = None): global apiKey, ipStackKey if (city == None): send_url = 'http://api.ipstack.com/' + str(get_ip()) + '?access_key=' + ipStackKey r = requests.get(send_url) j = json.loads(r.text) lat, lon = j['latitude'], j['longitude'] else: lat, lon = WeatherIntent.getLatLon(city); cityForcast = forecast(apiKey, lat, lon) # at this point we have to lat, lon url = 'https://api.darksky.net/forecast/' + apiKey + '/' + str(lat) + ',' + str(lon) + '?units=si' r = requests.get(url) j = json.loads(r.text) summary = '' if (j['hourly']): summary = j['hourly']['summary'] j = j['currently'] cityName = WeatherIntent.getCityName(lat, lon); return { 'weather': j['summary'], 'temp': j['temperature'], 'icon': j['icon'], 'city': cityName, 'summary': summary }
def dump_weather_for_t(t: datetime = datetime(year=2018, month=5, day=3).isoformat(), location: tuple = (42.36, -71.05), dry_run=True): if not os.path.isdir(f'weather-data-output/{t}'): os.makedirs(f'weather-data-output/{t}') needs_new_request = False if len(saved_weather[t]) > 0: dists = np.linalg.norm(np.array(saved_weather[t]) - np.array(location), axis=1) dist_min_ind = np.argmin(dists) try: dist_min = dists[dist_min_ind] except IndexError: dist_min = dists # just one entry if dist_min > 0.1: # 0.1deg is about 7 miles needs_new_request = True else: needs_new_request = True if not needs_new_request: coords_cached = saved_weather[t][dist_min_ind] out_filename = f'weather-data-output/{t}/{coords_cached[0]}_{coords_cached[1]}.json' elif needs_new_request and not dry_run: out = forecast(key, latitude=location[0], longitude=location[1], time=t) out_filename = f'weather-data-output/{t}/{location[0]}_{location[1]}.json' with open(out_filename, 'w') as f: json.dump(out['hourly'], f) saved_weather[t].append([location[0], location[1]]) return out_filename
def index(): """Get weather, render index.html""" BERKELEY = 37.877360, -122.296730 #Lat, long of Berkeley with forecast(dark_sky, *BERKELEY) as berkeley: weekday = date.today() weekly_summary = [] max_temp_array = [] for day in berkeley.daily: day = dict(day=date.strftime(weekday, '%a'), sum=day.summary, tempMin=day.temperatureMin, tempMax=day.temperatureMax) min_temp_in_celcius = helpers.convert_fahrenheit_to_celcius( day['tempMin']) max_temp_in_celcius = helpers.convert_fahrenheit_to_celcius( day['tempMax']) max_temp_array.append(max_temp_in_celcius) weekly_summary_string = day['day'] + ': ' + day[ 'sum'] + ' Temp range: ' + str( min_temp_in_celcius) + '-' + str(max_temp_in_celcius) weekly_summary.append(weekly_summary_string) weekday += timedelta(days=1) return render_template("index.html", weekly_report=berkeley.daily, weekly_summary=weekly_summary, max_temp_array=max_temp_array)
def get_hourly_weather_1day(self, city, time): city_forecast = forecast(key=self.key, latitude=city.latitude, longitude=city.longitude, time=time) return city_forecast['hourly']['data']
def darksky_config(latitude: float, longitude: float): """ This method connects to DarkSky using my API key and returns the current weather at a chosen location. Right now it only returns stirling weather data. """ requested_forecast = [] regex = r"[0-9][°F]" #used for converting the summary string regex_num = r"[0-9]" #used for converting the summary string numbers API_KEY = "0208ba7f74f919e0411ff251ce738b7f" location = darksky.forecast(API_KEY, latitude, longitude) weekday = datetime.date.today() with location: daily_sum = location.daily.summary for i in daily_sum.split(): if (re.search(regex, i)): numbers = re.findall(regex_num, i) temperature = numbers[0] + numbers[1] new_temp = convert_units(int(temperature), 2) daily_sum = daily_sum.replace(i, new_temp) requested_forecast.append(daily_sum) for day in location.daily: day = dict(day=datetime.date.strftime(weekday, '%a'), sum=day.summary, temp_min=convert_units(day.temperatureMin), temp_max=convert_units(day.temperatureMax)) requested_forecast.append( '{day}: {sum} Temp Range: {temp_min} - {temp_max}'.format( **day)) # **kwargs for passing keyworded data weekday += datetime.timedelta(days=1) return requested_forecast
def seven_days_forecast(coordinates): try: with forecast(API_KEY, *coordinates, units='si') as city_forecast: return (city_forecast['daily']['data']) except (Exception): print("API request error!") raise
def main(): #now = datetime.now().strftime("%H:%M:%S") #log into database db = MySQLdb.connect( 'localhost', # The Host 'BaseUser', # username 'password', # password 'mydb') # name of the data base cursor = db.cursor() #get mountain info coordinates = getCoordinates() MID = 1 #update each mountain's hourly and daily for mountain in coordinates: weather = forecast(DARK_SKY_KEY, mountain[1], mountain[2]) updateHourly(db, cursor, MID, weather.hourly) updateDaily(db, cursor, MID, weather.daily) MID += 1 print("Updated " + mountain[0]) print("Database successfully updated!") cursor.close()
def get_forecast(self, last_update_time): if (time.time() - last_update_time) > config.DS_CHECK_INTERVAL: syslog.syslog("Fetching update from DarkSky") try: self.weather = forecast(config.DS_API_KEY, config.LAT, config.LON, exclude='minutely', units=config.UNITS, lang=config.LANG) sunset_today = datetime.datetime.fromtimestamp( self.weather.daily[0].sunsetTime) if datetime.datetime.now() < sunset_today: index = 0 sr_suffix = 'today' ss_suffix = 'tonight' else: index = 1 sr_suffix = 'tomorrow' ss_suffix = 'tomorrow' self.sunrise = self.weather.daily[index].sunriseTime self.sunrise_string = datetime.datetime.fromtimestamp( self.sunrise).strftime("%I:%M %p {}").format(sr_suffix) self.sunset = self.weather.daily[index].sunsetTime self.sunset_string = datetime.datetime.fromtimestamp( self.sunset).strftime("%I:%M %p {}").format(ss_suffix) # start with saying we don't need an umbrella self.take_umbrella = False icon_now = self.weather.icon icon_today = self.weather.daily[0].icon if icon_now == 'rain' or icon_today == 'rain': self.take_umbrella = True else: # determine if an umbrella is needed during daylight hours curr_date = datetime.datetime.today().date() for hour in self.weather.hourly: hr = datetime.datetime.fromtimestamp(hour.time) sr = datetime.datetime.fromtimestamp( self.weather.daily[0].sunriseTime) ss = datetime.datetime.fromtimestamp( self.weather.daily[0].sunsetTime) rain_chance = hour.precipProbability is_today = hr.date() == curr_date is_daylight_hr = hr >= sr and hr <= ss if is_today and is_daylight_hr and rain_chance >= .25: self.take_umbrella = True break except requests.exceptions.RequestException as e: print('Request exception: ' + str(e)) return False except AttributeError as e: print('Attribute error: ' + str(e)) return False return round(time.time()) # new last_update_time return last_update_time
def test_pickle(self): location = -77.843906, 166.686520 # McMurdo station, antarctica # This doesn't actually hit the API since we mocked out the request lib forecast = darksky.forecast('test_key', *location) # Make sure we got the right data, via our mock self.assertEqual(forecast.currently.temperature, -23.58) # Ensure pickling by actually pickling with open('./forecast.pickle', 'wb') as outfile: pickle.dump(forecast, outfile) # Check that the file exists self.assertTrue(os.path.exists('./forecast.pickle'))
def _get_weather(self, request, force_update, weather_cookie): """Get Current Weather Based on IP Address Based on the current ip location, getthe current weather (or use NY if location is not available.) Save that data to a cookie to reduce # of api calls. Arguments: request -- A Flast Request force_update {bool} -- Should we force update the weather data weather_cookie -- Stored weather data """ # Get current weather for location based on IP if weather_cookie and not force_update: from_cookie = True; current_weather = json.loads(weather_cookie) else: from_cookie = False # fallback latitute/longitude data test_latlngs = { 'newyork': [40.7081, -73.9571], 'hawaii': [19.8968, 155.5828], 'trinidad': [10.65, -61.5167], 'sweden': [60.1282, 18.6435], 'australia': [25.2744, 133.7751], } default_latlng = test_latlngs['newyork'] # Get the visitors IP and lat/lng for that IP ip = request.headers.get('X-Forwarded-For', request.remote_addr) geo = geocoder.ip(ip) if ip != '127.0.0.1' else None lat, lng = geo.latlng if geo and len(geo.latlng) == 2 else default_latlng # Use Darksky to get the current forcast for that lat/lng geo_forecast = forecast(FORECAST_KEY, lat, lng) # Get and format the current weather daily_weather = geo_forecast['daily']['data'][0] current_weather = geo_forecast['currently'] current_weather['timezone'] = geo_forecast['timezone'] current_weather['units'] = geo_forecast['flags']['units'] # F or C current_weather['sunriseTime'] = daily_weather['sunriseTime'] current_weather['sunsetTime'] = daily_weather['sunsetTime'] current_weather['ip'] = ip current_weather['lat_lng'] = [lat, lng] return {'current': current_weather, 'from_cookie': from_cookie}