def current_temp_will(self, message=None, location=None): """what's the temperature (in _______): I know how to tell you the temperature!""" geolocator = Nominatim() if location is None: forecast = forecastio.load_forecast(FORECAST_API_KEY, LINCOLN_LAT, LINCOLN_LNG, units="us") currently = forecast.currently() temp = currently.temperature feels_like = currently.apparentTemperature combined = "It's currently %sF and feels like %sF here in Lincoln, NE" % (temp, feels_like) self.save("local_temp", combined) if message: return self.say(combined, message=message) else: geolocation = geolocator.geocode(location) lat = geolocation.latitude lng = geolocation.longitude forecast = forecastio.load_forecast(FORECAST_API_KEY, lat, lng, units="us") currently = forecast.currently() temp = currently.temperature feels_like = currently.apparentTemperature full_address = geolocation.address combined = "It's currently %s degrees and feels like %s degrees in %s" % (temp, feels_like, full_address) self.save(full_address + "_temp", combined) if message: self.say(combined, message=message)
def weather(): try: forecast = forecastio.load_forecast(os.environ["forecastio_key"], request.query.lat, request.query.lng) except: # For now, catch all errors; we should just catch Bottle HTTPErrors forecast = forecastio.load_forecast(os.environ["forecastio_key"], UserConstants.DefaultLat, UserConstants.DefaultLng) current_weather = forecast.currently().__dict__["d"]["summary"] return SparkCoreConstants.WeatherStart + str(generate_return_str(current_weather)) + SparkCoreConstants.Delimiter
def test_invalid_key(self): self.api_key = "not a real key" try: forecastio.load_forecast(self.api_key, self.lat, self.lng) self.assertTrue(False) # the previous line should throw an exception except requests.exceptions.HTTPError as e: self.assertEqual(str(e), "403 Client Error: Forbidden")
def test_invalid_param(self): self.lat = "" try: forecastio.load_forecast(self.api_key, self.lat, self.lng) self.assertTrue(False) # the previous line should throw an exception except requests.exceptions.HTTPError as e: self.assertEqual(str(e), "400 Client Error: Bad Request")
def __init__(self, _id, _keyfile, _lat, _lng): self.mod_id = _id self.lat = _lat self.lng = _lng self.weather_font = font.Font("weathericons.ttf",300) self.mod_rect = Rect((50,0), self.weather_font.size('\uf00d ')) with open(_keyfile, 'r') as f: self.api = f.read()[:-1] forecastio.load_forecast(self.api, self.lat, self.lng, units = "us", callback=self.request_callback)
def test_invalid_key(self): self.api_key = 'not a real key' try: forecastio.load_forecast( self.api_key, self.lat, self.lng ) self.assertTrue(False) # the previous line should throw an exception except requests.exceptions.HTTPError as e: self.assertTrue(str(e).startswith('400 Client Error: Bad Request'))
def pullOne(tracker,location,timing,number): readValues = dict() values = tracker['values'] if type(timing) is str and timing != 'null': timing = parser.parse(timing) elif timing == 'null': timing = datetime.datetime.now() row = {'place':location['place'],'lat':location['lat'],'lon':location['lon']} tries = 0 done = False maxTries = 10 while not done and tries != maxTries: if number == 'null': login = tracker['login'][0]['key'] else: login = random.choice(tracker['login'])['key'] time.sleep(random.uniform(0,2)) try: if timing != 'null': weatherIn = forecastio.load_forecast(login, location['lat'], location['lon'], timing) else: weatherIn = forecastio.load_forecast(login, location['lat'], location['lon']) pulledWeather = eval("weatherIn."+tracker['timing']) for valKey,value in values.iteritems(): try: attribute = eval("pulledWeather."+value) readValues[valKey] = attribute except: None done = True except: if len(tracker['login'])>1: print "Weather pull", tries, "failed, will sleep 30 seconds and retry with alternate key" tries += 1 time.sleep(30) else: print "Weather pull", tries, "failed, will sleep for 5 minutes and try again" tries += 1 time.sleep(300) if tries == maxTries: weatherIn = 'null' print "Error: could not pull weather for", location['place'],time return weatherIn , dict(row.items()+readValues.items())
def forecast(self, timely="current"): cache_data = self.data_handler.read_cache() user_location = self.profile.get_location() parsed_user_location = parse.quote(user_location) # user_location is Korean if parsed_user_location in cache_data: address = cache_data[parsed_user_location]["address"] lat = cache_data[parsed_user_location]["lat"] lon = cache_data[parsed_user_location]["lon"] else: geolocator = Nominatim(user_agent="kino-bot") location = geolocator.geocode(user_location) address = location.address lat = location.latitude lon = location.longitude self.data_handler.edit_cache( (parsed_user_location, {"address": address, "lat": lat, "lon": lon}) ) api_key = Config.open_api.dark_sky.TOKEN dark_sky = forecastio.load_forecast(api_key, lat, lon) if timely == "current": currently = dark_sky.currently() self.__forecast(currently, timely, address) elif timely == "daily": hourly = dark_sky.hourly() self.__forecast(hourly, timely, address) elif timely == "weekly": daily = dark_sky.daily() self.__forecast(daily, timely, address)
def weather(query): results = [] forecast = forecastio.load_forecast('fa4410dea9d5faaf6b54c606b9f2030c', *coord, units='si') daily = forecast.daily() if daily.data[0].time < datetime.datetime.now(): del daily.data[0] # summary for this week results.append({ "Title": 'This Week: {}'.format(daily.summary), "SubTitle": '', "IcoPath": icons_dir + icons.get(daily.icon, '') }) # daily summary for the next 5 days for day in daily.data[:5]: results.append({ "Title": '{}: {}'.format(weekdays[day.time.weekday()], day.d['summary']), "SubTitle": 'High: {}°C \tLow: {}°C \tPressure: {:.2f}mm \tWind: {}m/s \tRain: {}%'.format( day.d['temperatureMax'], day.d['temperatureMin'], day.d['pressure']*0.7501, day.d['windSpeed'], day.d['precipProbability']*100), "IcoPath": icons_dir + icons.get(day.d['icon'], '') }) if not results: results.append({ "Title": 'Not found', "SubTitle": '', "IcoPath":"Images/app.png" }) return results
def handle(text, mic, profile): """ Responds to user-input, typically speech text, with a summary of the relevant weather for the requested date (typically, weather information will not be available for days beyond tomorrow). Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ api_key = profile['keys']['forecastio'] lat = profile['loc']['lat'] long = profile['loc']['long'] forecast_time = datetime.datetime.now() if bool(re.search(r'\b(tonight)\b', text, re.IGNORECASE)): forecast_time = datetime.datetime.combine(datetime.datetime.now().date(),datetime.time(hour=21)) elif bool(re.search(r'\b(tomorrow)\b', text, re.IGNORECASE)): forecast_time = datetime.datetime.combine(datetime.datetime.now().date(),datetime.time(hour=12)) forecast_time = forecast_time + datetime.timedelta(days=1) forecast = forecastio.load_forecast(api_key,lat, long,time=forecast_time) response = "The forecast is " + forecast.currently().summary + " with a temperature of " response = response + "%2d and a %2d percent chance of precipitation" response = response % (forecast.currently().temperature, forecast.currently().precipProbability*100) mic.say(response)
def main(): """ Run load_forecast() with the given lat, lng, and time arguments. """ api_key = "e3f8667cb539171dc2f4b389d33648ce" lat = -31.967819 lng = 115.87718 time = datetime.datetime(2015, 2, 27, 6, 0, 0) forecast = forecastio.load_forecast(api_key, lat, lng, time=time) print ("===========Currently Data=========") print (forecast.currently()) print ("===========Hourly Data=========") by_hour = forecast.hourly() print ("Hourly Summary: %s" % (by_hour.summary)) for hourly_data_point in by_hour.data: print (hourly_data_point) print ("===========Daily Data=========") by_day = forecast.daily() print ("Daily Summary: %s" % (by_day.summary)) for daily_data_point in by_day.data: print (daily_data_point)
def show_forecast(): dayToShow = 0 if(datetime.datetime.now().hour > 17): dayToShow = 1 lcd.set_backlight(1) lcd.show_cursor(True) lcd.blink(True) lcd.message("Fetching\nForecast") time.sleep(1.0) # Sleep a second to build suspense, API is fast! forecast = forecastio.load_forecast(forecastio_api_key, lat, lng) current = forecast.currently() temp = str(int(round(current.temperature))) byDay = forecast.daily() today = byDay.data[dayToShow] summary = today.summary line1 = today.time.strftime('%A') hi = str(int(round(today.temperatureMax))) lo = str(int(round(today.temperatureMin))) line2 = temp + "F L:" +lo + " H:" + hi lcd.clear() lcd.message(line1 + "\n" + line2) lcd.show_cursor(False) lcd.blink(False) time.sleep(5.0) lcd.set_backlight(0) lcd.clear()
def weather_alerts(self, forced=False): if not forced: if self.load("check_weather_alerts", False) is False: return False print "Checking for severe weather alerts" current_alerts = self.load("current_alerts", {}) forecast = forecastio.load_forecast(FORECAST_API_KEY, LINCOLN_LAT, LINCOLN_LNG, units="us") has_alerted = False alerts = forecast.alerts() if alerts: for alert in alerts: if str(alert.uri) not in current_alerts.keys(): if not has_alerted: self.say( "Severe Weather Alert(s) have been detected.", room=self.available_rooms["Antitankcrew"], color="red", alert=True, ) alert_say = ( "Title: %s" "Expires: %s" "Description: %s" "More Information: %s" % (alert.title, alert.expires, alert.description, str(alert.uri)) ) current_alerts[str(alert.uri)] = alert.expires self.say("/code " + alert_say, room=self.available_rooms["Antitankcrew"], color="red", notify=True) else: if current_alerts[str(alert.uri)] > time.time(): del current_alerts[str(alert.uri)] self.save("current_alerts", current_alerts)
def download_weather_data(api_key, lat, lng, weather_params, start, number_days): times = [] out = {k: [] for k in weather_params} for offset in range(1, number_days): print(start + datetime.timedelta(offset)) forecast = forecastio.load_forecast( api_key, lat, lng, time=start + datetime.timedelta(offset), units="us") h = forecast.hourly() d = h.data for p in d: times.append(p.time) for param in weather_params: if param in p.d: out[param].append(p.d[param]) else: out[param].append(np.NaN) df = pd.DataFrame(out, index=times) df = df.fillna(method='ffill') df = df.tz_localize("Asia/Kolkata") df = df.tz_convert("US/Central") return df
def at_start(self): if not self.db.API_key: self.db.API_Key = 'e07c570e1f5f85a42dacce70bc6c63ce' if not self.db.fogmessage: self.db.fogmessage = ['A mist hangs over everything','The fog turns everything into murky shadows','You worry about your footing in the dense fog'] self.db.clearmessage = ['The bright sky feels light and carefree','The energy of the earth refreshes you','A clear day','Sunlight warms your face','The trees are bright and green','You hear the laughter of undergrads','You wish you had a frisbee'] self.db.cloudmessage = ['Clouds sweep across the sky.','A faint breeze is felt','A cloud in the distance reminds you of something','Tree branches creak and sway in the wind','A chill comes over you','You see a mountain in the distance'] self.db.rainmessage = ['The rain falls heavily on the ground','The dark clouds are pregnant with rain','The ground is slick, be careful','Rain, rain, go away, come again some other day'] self.db.snowmessage = ['White snow blankets the world','The cold bites at your face'] self.db.raremessage = ['You feel a pang of nostalgia','A faint smell reminds you of your mother','The air tastes like metal','You feel hopeless and lost','The meaninglessness of existence overcomes you','There\'s some trash on the ground','There doesn\'t seem to be anyone around','You notice the hum of electricity. Has it always been there?','The wounds of your childhood ache'] # search for veggies in room veggies_in_room = [obj for obj in self.obj.contents_get() if utils.inherits_from(obj, objects.Vegetable)] # if not veggies in room if not veggies_in_room: prototype = random.choice(self.db.available_veggies) # use the spawner to create a new Vegetable from the spawner dictionary veggie = spawn(objects.VEGETABLE_PROTOTYPES[prototype], prototype_parents=objects.VEGETABLE_PROTOTYPES)[0] veggie.location = self.obj veggiestring = ("A %s ripens" % veggie) self.obj.msg_contents(veggiestring) self.obj.msg_contents("DATA,obj_add," + veggie + veggie.dbref) # if weather not set for room if not self.db.cweather and self.db.location: loc = self.obj.db.location.split(',') # if location contains lat, lng if len(loc)==2: # Get Weather from Forecast.io forecast = forecastio.load_forecast(self.db.API_Key, loc[0], loc[1]) # Extract and store current weather summary self.obj.cweather = forecast.currently().summary
def update(self): """ Gets the latest data from Forecast.io. """ forecast = forecastio.load_forecast(self._api_key, self.latitude, self.longitude) self.data = forecast.currently()
def __init__(self, api_key, lat, lng): """ Initializes the WeatherForecast Class """ ### Variables Taken ### self.api_key = api_key self.lat = lat self.lng = lng ### Forecastio Related Variables to be Used ### self.forecast = forecastio.load_forecast(self.api_key, self.lat, self.lng) self.offset = self.forecast.offset() self.hourlyForecast = self.forecast.hourly() self.dailyForecast = self.forecast.daily() self.currentForecast = self.forecast.currently() ### Initializing Variables to Return ### self.maxTemp = None self.minTemp = None self.currentTemp = None self.precipProb = None self.dailySummary = None self.currentTime = datetime.datetime.now().replace(second=0, microsecond=0) self.precipProbability = [] self.maxPrecipProb = None self.icon = None
def update(self): """Gets the latest data from Forecast.io.""" import forecastio forecast = forecastio.load_forecast(self._api_key, self.latitude, self.longitude, units=self.units) self.data = forecast.currently() self.unit_system = forecast.json["flags"]["units"]
def compare_locations(current1, loc2): lat2, lng2 = loc2 forecast2 = forecastio.load_forecast(api_key, lat2, lng2) current2 = forecast2.currently() index1 = weather_index(current1) index2 = weather_index(current2) return current2, index1/index2, current2.icon, current2.temperature
def setup_platform(hass, config, add_devices, discovery_info=None): """Get the Forecast.io sensor.""" import forecastio if None in (hass.config.latitude, hass.config.longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return False try: forecast = forecastio.load_forecast(config.get(CONF_API_KEY, None), hass.config.latitude, hass.config.longitude) forecast.currently() except ValueError: _LOGGER.error("Connection error " "Please check your settings for Forecast.io.") return False if "units" in config: units = config["units"] elif hass.config.temperature_unit == TEMP_CELCIUS: units = "si" else: units = "us" data = ForeCastData(config.get(CONF_API_KEY, None), hass.config.latitude, hass.config.longitude, units) dev = [] for variable in config["monitored_conditions"]: if variable not in SENSOR_TYPES: _LOGGER.error('Sensor type: "%s" does not exist', variable) else: dev.append(ForeCastSensor(data, variable)) add_devices(dev)
def loadForecast(self, request): if self.isCasheValid(): return Forecast.cashe else: #print "Expunging weather cashe" try: lat=request.POST['lat'] lng = request.POST['lng'] except KeyError: raise Http404("bad request") forecast = forecastio.load_forecast(API_KEY, lat, lng) #Forecast.cashe=forecast #Forecast.cashe.time=datetime.datetime.now() unit = forecast.json.get("flags")["units"] if unit.lower() == 'us': self.tm = "F" self.windUnits = "MPH" elif unit.lower() == 'si': self.tm = "C" self.windUnits = "M/S" elif unit.lower() == "ca": self.tm = "C" self.windUnits = "Km/H" elif unit.lower() == "uk2": self.tm = "C" self.windUnits = "MPH" else: print "Units are as follows.", units self.tm, self.windUnits = "Error", "Error" return forecast
def get_forecast(socketio, app): ret = None api_key = app.config.get('FORECASTIO_API_KEY', None) lat = 40.5621700 lng = -111.9296580 if not api_key: return 'forecast', None try: forecast = forecastio.load_forecast(api_key, lat, lng) fc_hour = [hour.d for hour in forecast.hourly().data] fc_day = [day.d for day in forecast.daily().data] except Exception as e: raise e else: ret = { 'fc_now': forecast.currently().d, 'fc_day': fc_day, 'fc_hour': fc_hour } return 'forecast', ret
def test_with_time(self): forecast = forecastio.load_forecast( self.api_key, self.lat, self.lng, time=self.time ) self.assertEqual(forecast.response.status_code, 200)
def get_weather(): url = "http://ip-api.com/json/" if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] else: ip = request.remote_addr # uncomment for local testing # ip = "2601:602:9804:4396:8d29:6f17:a182:e8ed" list = [] r = requests.get(url+ip) json_string = json.dumps(r.json()) json_obj = json.loads(json_string) if json_obj['status'] == "fail" : return [url+ip, emojify("Something went wrong :bee: :sunny: :umbrella:")] forecast = forecastio.load_forecast(api_key, json_obj['lat'], json_obj['lon']) current = forecast.currently() if "Rain" not in current.summary: list.append(emojify(":sunny: It's Not Raining :sunny:")) else: list.append(emojify(":umbrella: It's Raining :umbrella:")) list.append(json_obj['city']) list.append(forecast.minutely().summary) list.append(forecast.hourly().summary) list.append(forecast.currently().temperature) return list
def main(): """ Run load_forecast() with the given lat, lng, and time arguments. """ api_key = "YOUR API KEY" lat = -31.967819 lng = 115.87718 time = datetime.datetime(2015, 2, 27, 6, 0, 0) forecast = forecastio.load_forecast(api_key, lat, lng, time=time) print "===========Currently Data=========" print forecast.currently() print "===========Hourly Data=========" by_hour = forecast.hourly() print "Hourly Summary: %s" % (by_hour.summary) for hourly_data_point in by_hour.data: print hourly_data_point print "===========Daily Data=========" by_day = forecast.daily() print "Daily Summary: %s" % (by_day.summary) for daily_data_point in by_day.data: print daily_data_point
def fuckingweather(bot, trigger): forecast = forecastio.load_forecast(API_KEY, lat, lng) now = forecast.currently() if now.icon in responses: bot.reply(responses[now.icon]) else: bot.reply("I have no f*****g clue!")
def __init__(self, api_key, latitude, longitude, **kwargs): """Initializes an instance of the ForecastIO wrapper""" self._api_key = api_key self._latitude = latitude self._longitude = longitude self._forecast = forecastio.load_forecast( self._api_key, self._latitude, self._longitude)
def fetch_weather(city, gdate, gtime): # Preparing Date, Time data for API calls (month, day, year) = map(int, gdate.split('/')) (hour, minute) = map(int, (gtime.split())[0].split(':')) # Handling AM/PM if (gtime.split())[1] == 'PM': if hour != 12: hour += 12 # Geo Location of a given city geoloc = googv3.geocode(city) # Time Zone for a given Latitude & Longitude tz = googv3.timezone((geoloc.latitude, geoloc.longitude)) #print city, tz logger.debug('City: %s, Time Zone: %s', city, tz) # Date in UTC Format date = datetime.datetime(year, month, day, hour, minute) #print date logger.debug('Date: %s', date) # Get Weather Information for given location & time forecast = forecastio.load_forecast(forecastIO_api_key, geoloc.latitude,\ geoloc.longitude, time=date) forecast_data = forecast.currently() #print forecast_data.d return forecast_data.d
def process_input(location): """ Takes and address string and displays a weather profile """ # geolocate address from supplied address string geolocator = Nominatim() try: target_location = geolocator.geocode(location, timeout=5) print "Target Location : " + target_location.address print "Co-ordinates ({0}, {1})".format(target_location.latitude, target_location.longitude) except GeocoderTimedOut: print "Error: Geocode failed due to timeout. Please try again in a few minutes" # Load API key api_key = fetch_api_key() # Load weather for location provided weather_forecast = forecastio.load_forecast(api_key, target_location.latitude, target_location.longitude) # Process Current weather hourly_weather = weather_forecast.hourly() hourly_table = PrettyTable() for hourly_data in hourly_weather.data[0:5]: hourly_table.add_column(hourly_data.time.strftime('%H:%M:%S'), [hourly_data.summary]) print "Current Weather:" print hourly_table # Process weekly forecast daily_weather = weather_forecast.daily() forecast_table = PrettyTable(["Date", "Forecast Summary"]) for daily_data in daily_weather.data: forecast_table.add_row([daily_data.time.strftime('%m/%d/%Y'), daily_data.summary]) print "Forecast for the next few days" print forecast_table
def main(): """Get the current forecast from Forecast.io.""" # Read the config file and get the goodies config = configparser.ConfigParser() config.read('../config/config.ini') # Set all of the variables we need for Forecast.io api_key = config['Forecastio']['api_key'] lat = config['Forecastio']['default_lat'] lon = config['Forecastio']['default_lon'] # Authenticate with Forecast.io and get the current forecast try: f = forecastio.load_forecast(api_key, lat, lon) forecast = f.daily() # Get the forecast summary f_summary = forecast.data[0].summary[:-1].lower() # Get the rest of the temps for the day f_min_temp = int(round(forecast.data[0].temperatureMin)) f_max_temp = int(round(forecast.data[0].temperatureMax)) # Create the forecast print("It is going to be {} with temperatures between {} and {}" " degrees".format(f_summary, f_min_temp, f_max_temp)) except: print("nable to retrieve the current weather forecast")
def getForecasts(lat, lng, forecast_key, city, Job_Dir, out_file): logging.info('====== Started fetching forecasts: {} ======='.format( city.title())) print("Started fetching forecasts for " + city.title() + ' ({}, {})'.format(lat, lng)) #utcnow is a naive datetime, so have to set the timezone to utc current_time = datetime.datetime.utcnow().replace(tzinfo=tz.utc) #forecast io returns weather data for time provided and 24 hrs before, #so we request 29 days back instead of 30 date = 365 * 4 #download four years of data when first starting a city start = (current_time - datetime.timedelta(days=date)).replace( minute=0, second=0, microsecond=0) endtime = (current_time + datetime.timedelta(days=0)).replace( minute=0, second=0, microsecond=0) i = 0 window_count = 0 json = [] timezone = None while i <= ( date + 0 ): #looks up forecasts for each hour for (date+0) days - date days in the past and 0 days in the future hour = 0 lookUpTime = start + datetime.timedelta(days=i) forecast = forecastio.load_forecast(forecast_key, lat, lng, time=lookUpTime) timezone = forecast.json['timezone'] for hourlyData in forecast.hourly().data: thisHour = hourlyData.time.replace(tzinfo=tz.utc) if thisHour < start or thisHour >= endtime: #Forecast.io returns data starting from midnight prior to the day requested. #Some of this might be extraneous, so must check to see if the time #of the hourly object is before the start time. Note start time is #one day ahead. continue window = int( ceil((thisHour - current_time).total_seconds() / SECONDSPERHOUR)) if window >= 0: window_count += 1 json.append({ 'hournumber': hour, 'year': current_time.year, 'wind_speed': getAttr(hourlyData, 'windSpeed', 0), 'hr': thisHour, 'relative_humidity': getAttr(hourlyData, 'humidity', 0) * 100, 'drybulb_fahrenheit': getAttr(hourlyData, 'temperature', 0), 'hourly_precip': getAttr(hourlyData, 'precipIntensity', 0), 'precip_probability': getAttr(hourlyData, 'precipProbability', 0), 'apparent_temperature': getAttr(hourlyData, 'apparentTemperature', 0), 'weather_type': getAttr(hourlyData, 'icon', 0), 'dew_point': getAttr(hourlyData, 'dewPoint', 0), 'wind_gust': getAttr(hourlyData, 'windGust', 0), 'wind_bearing': getAttr(hourlyData, 'windBearing', 0), 'visibility': getAttr(hourlyData, 'visibility', 0), 'cloud_cover': getAttr(hourlyData, 'cloudCover', 0), 'pressure': getAttr(hourlyData, 'pressure', 0), 'dod1_drybulb_fahrenheit': 0, 'dod2_drybulb_fahrenheit': 0, 'dod3_drybulb_fahrenheit': 0, 'wow1_drybulb_fahrenheit': 0, 'wow2_drybulb_fahrenheit': 0, 'hour_count_since_precip': -1, 'precip_hour_cnt_in_last_1_week': 0, 'precip_hour_cnt_in_last_1_day': 0, 'precip_hour_cnt_in_last_3_day': 0, 'window': int(window) }) hour += 1 i += 1 df = pd.DataFrame(json) #iterates from 720 to 791, the weather forecasts for the next 3 days relevant = len(df) - len(df[df['window'] >= 0]) ##STP: drop 109-146 # #legacy code... not sure what is going on # for i in range(relevant, len(df)): # df.ix[i,'dod1_drybulb_fahrenheit'] = df.ix[ # i,'drybulb_fahrenheit'] - df.ix[i-24,'drybulb_fahrenheit'] # df.ix[i,'dod2_drybulb_fahrenheit'] = df.ix[ # i,'drybulb_fahrenheit'] - df.ix[i-48,'drybulb_fahrenheit'] # df.ix[i,'dod3_drybulb_fahrenheit'] = df.ix[ # i,'drybulb_fahrenheit'] - df.ix[i-72,'drybulb_fahrenheit'] # df.ix[i,'wow1_drybulb_fahrenheit'] = df.ix[ # i,'drybulb_fahrenheit'] - df.ix[i-168,'drybulb_fahrenheit'] # df.ix[i,'wow2_drybulb_fahrenheit'] = df.ix[ # i,'drybulb_fahrenheit'] - df.ix[i-336,'drybulb_fahrenheit'] # for j in range(1,i): # if df.ix[i - j,'hourly_precip'] > .001: # df.ix[i,'hour_count_since_precip'] = j # break # precip_1wk_cnt = 0 # precip_1d_cnt = 0 # precip_3d_cnt = 0 # for k in range(1, 168): # if df.ix[i - k,'hourly_precip'] > .001: # if k <= 24: # precip_1d_cnt += 1 # precip_1wk_cnt+=1 # precip_3d_cnt+=1 # elif k <= 72: # precip_1wk_cnt+=1 # precip_3d_cnt+=1 # else: # precip_1wk_cnt+=1 # df.ix[i,'precip_hour_cnt_in_last_1_week'] = precip_1wk_cnt # df.ix[i,'precip_hour_cnt_in_last_1_day'] = precip_1d_cnt # df.ix[i,'precip_hour_cnt_in_last_3_day'] = precip_3d_cnt # # not sure what this was doing, but it doesn't make sense # # changing it to all rows >= 0, which keeps all rows for the next 72 hrs # # old: df = df[(df['window'] >= -5) & (df['window'] < 66)] # df = df[(df['window'] >= 0)] # df = df.drop('window', 1) # Make sure the local timezone is used. localTime = current_time.astimezone(tz.timezone(timezone)) df['prediction_timestamp'] = localTime.strftime('%b %d, %Y %H:%M') local_tz = tz.timezone(timezone) df.index = df['hr'] df['hr'] = df.index.tz_convert(local_tz) df['prediction_timestamp'] = localTime.strftime('%b %d, %Y %H:%M') df[[ 'hr', 'wind_speed', 'relative_humidity', 'hourly_precip', 'drybulb_fahrenheit', 'precip_probability', 'apparent_temperature', 'weather_type', 'dew_point', 'wind_gust', 'wind_bearing', 'visibility', 'cloud_cover', 'pressure' ]].to_csv(Job_Dir + '/weather.csv', index=False)
def answer_message(self, slack_event): event_type = slack_event["event"]["type"] user_id = slack_event["event"]["user"] channel = slack_event["event"]["channel"] incoming_message = slack_event["event"]["text"] message_words = re.sub(r"[^\w]", " ", incoming_message).split() if len(set(message_words).intersection(set(offensive_words))) > 0: self.client.api_call("chat.postMessage", channel=channel, username=self.name, as_user=self.as_user, text="Cuida tu lenguaje, <@%s> https://media.giphy.com/media/GBIzZdF3AxZ6/giphy.gif" % user_id ) return if self.is_channel(channel) and event_type == "message": return if any(s in incoming_message.upper() for s in next_event_messages): next_event = self.next_event() self.client.api_call("chat.postMessage", channel=channel, username=self.name, as_user=self.as_user, text="El próximo evento será el viernes %s de 18:30 hasta las 20:30" % next_event.strftime( "%d de %B") ) elif any(s in incoming_message.upper() for s in forescat_messages): next_event = self.next_event() forecast = forecastio.load_forecast(key=config.get( "forecast.io", "secret_key"), lat=santander[0], lng=santander[1], lang="es", time=datetime.datetime.combine(next_event, datetime.time(18, 30, 0))) text = "Viernes %s // %s // ↑ %sºC - ↓ %sºC" % (next_event.strftime("%d de %B"), forecast.daily( ).data[0].summary, int(round(forecast.daily().data[0].temperatureHigh)), int(round(forecast.daily().data[0].temperatureLow))) self.client.api_call("chat.postMessage", channel=channel, username=self.name, as_user=self.as_user, text=text ) elif any(s in incoming_message.upper() for s in greetings_messages): self.client.api_call("chat.postMessage", channel=channel, username=self.name, as_user=self.as_user, text="Hola %s" % self.get_username(user_id) ) elif any(s in incoming_message.upper() for s in thanks_messages): self.client.api_call("chat.postMessage", channel=channel, username=self.name, as_user=self.as_user, text="Las que tu tienes" ) elif any(s in incoming_message.upper() for s in goodbyes_messages): self.client.api_call("chat.postMessage", channel=channel, username=self.name, as_user=self.as_user, text="Hasta la próxima" ) else: buttonUrl = 'https://www.google.com/search?q=%s' % incoming_message.replace( " ", "+") self.client.api_call("chat.postMessage", channel=channel, username=self.name, as_user=self.as_user, text='Me he quedado sin palabras, pero Google seguramente sepa la respuesta.', attachments=[{ 'fallback': buttonUrl, 'actions': [{'type': 'button', 'text': 'Buscar :mag:', 'url': buttonUrl, 'style': 'primary'}] }] ) return
def get_temperature(): forecast = load_forecast(API_KEY, 52.0056394, 4.351788) return forecast.currently().temperature
b.get_api() b.set_light(3, 'on', True) b.set_light(3, 'sat', 255) b.set_light(3, 'bri', 255) b.set_light(2, 'on', True) b.set_light(2, 'sat', 255) b.set_light(2, 'bri', 255) counter = 0 api_key = "14240dd5d3bf601df4eb9fee104134cc" lat = 41.909506 lng = -87.685113 forecast = forecastio.load_forecast(api_key, lat, lng, time=None, units="us") current = forecast.currently() currentTemp = current.temperature condition = current.icon #icons icon_clear_day = "clear-day" icon_rain = "rain" icon_snow = "snow" icon_sleet = "sleet" icon_wind = "wind" icon_fog = "fog" icon_cloudy = "cloudy" icon_partly_cloudy_day = "partly-cloudy-day" # for min1 in byHour.data:
def getCurrentTemp(): forecast = forecastio.load_forecast(api_key, lat, lng) byHour = forecast.hourly() return forecast.currently().temperature
AppConfig(new_app, configfile) return new_app # Loads settings from default_config.py, then from a .cfg file specified in DOORBOARD_CONFIG env var, # then from any environment variables prefixed with DOORBOARD_ app = create_app() app.secret_key = app.config.get('SECRET_KEY') or os.urandom(24) api_key = app.config.get('FORECASTIO_API_KEY') home = (app.config.get('HOME_LAT'), app.config.get('HOME_LONG')) update_delay = datetime.timedelta(seconds=app.config.get('UPDATE_DELAY')) last_updated = datetime.datetime.now() - update_delay last_weather = forecastio.load_forecast(api_key, *home) def update_weather(): global last_weather, last_updated if last_updated + update_delay <= datetime.datetime.now(): try: last_updated = datetime.datetime.now() last_weather = forecastio.load_forecast(api_key, *home) except Exception: pass @app.template_filter('dayname') def dayname(date):
loc = " ".join(sys.argv[1:]) geo = geocoder.google(loc) else: geo = loc.getLoc() if not geo.ok: print("Couldn't find location.") quit() header = '========= Forecast for {}, {} ==========' print(header.format(geo.city, geo.state)) key = "df74ca2b28b972e0782399de41a31256" forecast = forecastio.load_forecast(key, geo.latlng[0], geo.latlng[1], units='us') temp = int(forecast.currently().temperature) d = forecast.daily() now = datetime.datetime.now().day for df in d.data: date = u'\033[1mTODAY: {}\N{DEGREE SIGN}'.format(temp) if (now != df.time.day): date = df.time.strftime('%a %b %d') high = int(df.temperatureMax) low = int(df.temperatureMin) fmt = u'{} {}\N{DEGREE SIGN}-{}\N{DEGREE SIGN} {}\033[0m' print(fmt.format(date, high, low, df.summary))
def displayWeather(self, timeFrameUserVal): textReturn = "" api_key = "ece623732956ab6653653c4cec4247fa" #load the forcast for the latitute and longitude forecast = forecastio.load_forecast(api_key, self.lat, self.lng) timeFrameUser = timeFrameUserVal #"today" #Based on what time frame the user chose, display weather if timeFrameUser == "hourly": timeFrame = forecast.hourly() textReturn += timeFrame.summary self.jsonObj[0]["summary"] = str(timeFrame.summary) textReturn += "\n" textReturn += timeFrame.icon self.jsonObj.append({ "summary" : str(timeFrame.summary) , "icon" : str(timeFrame.icon) }) textReturn += "\n\n" listOfTemps = [] numHour = 0 textReturn += "Hourly temperature for today" for onePieceData in timeFrame.data: if numHour < 24: numHour += 1 textReturn += "Time: " + str(numHour) + "\n" textReturn += str(onePieceData.temperature) + "\n" self.jsonObj.append({ str(numHour) + "Hr" : str(onePieceData.temperature) , "icon" : str(timeFrame.icon)}) elif timeFrameUser == "today": listOfTemps = [] numHour = 0 timeFrame = forecast.currently() textReturn += timeFrame.summary + "\n" textReturn += timeFrame.icon + "\n" textReturn += "average temperature for the day: " + str(timeFrame.temperature) self.jsonObj.append({ "summary" : str(timeFrame.summary), "icon" : str(timeFrame.icon), "avg" : str(timeFrame.temperature) }) timeFrame = forecast.hourly() for onePieceData in timeFrame.data: if numHour < 24: numHour += 1 listOfTemps.append(str(onePieceData.temperature)) textReturn += "\n" + "min value for today : " + str(min(listOfTemps)) + "\n" textReturn += "max value for today : " + str(max(listOfTemps)) self.jsonObj.append({ "min" : str(min(listOfTemps)), "max" : str(max(listOfTemps)) }) elif timeFrameUser == "weekly": timeFrame = forecast.daily() textReturn += timeFrame.summary + "\n" textReturn += timeFrame.icon self.jsonObj.append({ "summary" : str(timeFrame.summary), "icon" : str(timeFrame.icon) }) else: textReturn += "Format of your text should be 'WEATHER: hourly' or 'WEATHER: today' or 'WEATHER: weekly'" if textReturn == "": self.jsonObj.append({ "success" : "false" }) else: self.jsonObj.append({ "success" : "true" }) return textReturn
def get_current(): fio = forecastio.load_forecast(FORECAST_API_KEY, HOME_LAT, HOME_LONG) now = fio.currently() return now.d
from secrets import * import tweepy import forecastio import time auth = tweepy.OAuthHandler(C_KEY, C_SECRET) auth.set_access_token(A_TOKEN, A_TOKEN_SECRET) api = tweepy.API(auth) latitude = 40.98 longitude = -73.81 #load forecast for specific latitude and longitude forecast = forecastio.load_forecast(api_key, latitude, longitude) byDay = forecast.daily() tweet = (byDay.summary) api.update_status(tweet, latitude, longitude) #print(api.me()) #print(api.verify_credentials()) #print(api.rate_limit_status()) my_file = open('primes1.txt', 'r') file_lines = my_file.readlines()
ForecastTime = now.strftime("%Y-%m-%d %H:%M") ''' Set the start date to either a specific day or a specific lag ''' #a = datetime.date(2014,12,1) a = datetime.datetime.today() - datetime.timedelta(1) numdays = 7 # Set the number of days to pull in the future '''Set the Date array''' dateList = [] for x in range(0, numdays): dateList.append(a + datetime.timedelta( days=x)) # Can change the '+' to '-' to pull historical '''Loop through the locations and dates''' temps = [] for i in range(len(locations)): for dates in dateList: forecast = forecastio.load_forecast(api_key, lats[i], lngs[i], dates) byHour = forecast.hourly() for hourlyData in byHour.data: try: temps.append({ 'ForecastDate': ForecastTime, 'Time': hourlyData.time.strftime("%Y-%m-%d %H:%M:%S"), 'Location': locations[i], 'Temp': hourlyData.temperature, 'DewPoint':
def start(lat, lng, item): api_key = open("apikey").read(300) forecast = forecastio.load_forecast(api_key, lat, lng) makeForecast(forecast, item)
def get_weather(api_key, lat, lng): forecast = forecastio.load_forecast(api_key, lat, lng).currently() return print("It is currently % degrees." % (forecast.temperature))
def get_forecast(): return forecastio.load_forecast(api_key, lat, lng)
def writeEvent(lat, lng, year, month, day, outcome): lat = lat lng = lng year = year month = month day = day outcome = outcome windGust = [] temperature = [] dewPoint = [] humidity = [] apparentTemperature = [] pressure = [] windSpeed = [] visibility = [] precipIntensity = [] precipProbability = [] # Day before from 2pm - midnight date = datetime(year, month, day) - timedelta(1) forecast = forecastio.load_forecast(api_key, lat, lng, time=date, units="us") h = forecast.hourly() for y in range(14, 24): if (len(h.data) <= y): print("Not enough data for " + str(month) + "/" + str(day - 1) + "/" + str(year)) return data = h.data[y].d x = data.get('windGust', "none") if (x == "none"): x = 0 print("No data for windGust for " + str(month) + "/" + str(day - 1) + "/" + str(year) + " Hour " + str(y)) windGust.append(x) x = data.get('temperature', "none") if (x == "none"): x = 40 print("No data for temperature for " + str(month) + "/" + str(day - 1) + "/" + str(year) + " Hour " + str(y)) temperature.append(x) x = data.get('dewPoint', "none") if (x == "none"): x = 35 print("No data for dewPoint for " + str(month) + "/" + str(day - 1) + "/" + str(year) + " Hour " + str(y)) dewPoint.append(x) x = data.get('humidity', "none") if (x == "none"): x = .5 print("No data for humidity for " + str(month) + "/" + str(day - 1) + "/" + str(year) + " Hour " + str(y)) humidity.append(x) x = data.get('apparentTemperature', "none") if (x == "none"): x = 40 print("No data for apparentTemperature for " + str(month) + "/" + str(day - 1) + "/" + str(year) + " Hour " + str(y)) apparentTemperature.append(x) x = data.get('pressure', "none") if (x == "none"): x = 1013 print("No data for pressure for " + str(month) + "/" + str(day - 1) + "/" + str(year) + " Hour " + str(y)) pressure.append(x) x = data.get('windSpeed', "none") if (x == "none"): x = 1 print("No data for windSpeed for " + str(month) + "/" + str(day - 1) + "/" + str(year) + " Hour " + str(y)) windSpeed.append(x) x = data.get('visibility', "none") if (x == "none"): x = 9.997 print("No data for visibility for " + str(month) + "/" + str(day - 1) + "/" + str(year) + " Hour " + str(y)) visibility.append(x) x = data.get('precipIntensity', "none") if (x == "none"): x = 0 print("No data for precipIntensity for " + str(month) + "/" + str(day - 1) + "/" + str(year) + " Hour " + str(y)) precipIntensity.append(x) x = data.get('precipProbability', "none") if (x == "none"): x = 0 print("No data for precipProbability for " + str(month) + "/" + str(day - 1) + "/" + str(year) + " Hour " + str(y)) precipProbability.append(x) # Day of from midnight to 3 pm date = datetime(year, month, day) forecast = forecastio.load_forecast(api_key, lat, lng, time=date, units="us") h = forecast.hourly() for y in range(0, 15): if (len(h.data) <= y): print("Not enough data for " + str(month) + "/" + str(day) + "/" + str(year) + str(y)) return data = h.data[y].d x = data.get('windGust', "none") if (x == "none"): x = 0 print("No data for windGust for " + str(month) + "/" + str(day) + "/" + str(year) + " Hour " + str(y)) windGust.append(x) x = data.get('temperature', "none") if (x == "none"): x = 40 print("No data for temperature for " + str(month) + "/" + str(day) + "/" + str(year) + " Hour " + str(y)) temperature.append(x) x = data.get('dewPoint', "none") if (x == "none"): x = 35 print("No data for dewPoint for " + str(month) + "/" + str(day) + "/" + str(year) + " Hour " + str(y)) dewPoint.append(x) x = data.get('humidity', "none") if (x == "none"): x = .5 print("No data for humidity for " + str(month) + "/" + str(day) + "/" + str(year) + " Hour " + str(y)) humidity.append(x) x = data.get('apparentTemperature', "none") if (x == "none"): x = 40 print("No data for apparentTemperature for " + str(month) + "/" + str(day) + "/" + str(year) + " Hour " + str(y)) apparentTemperature.append(x) x = data.get('pressure', "none") if (x == "none"): x = 1013 print("No data for pressure for " + str(month) + "/" + str(day) + "/" + str(year) + " Hour " + str(y)) pressure.append(x) x = data.get('windSpeed', "none") if (x == "none"): x = 1 print("No data for windSpeed for " + str(month) + "/" + str(day) + "/" + str(year) + " Hour " + str(y)) windSpeed.append(x) x = data.get('visibility', "none") if (x == "none"): x = 9.997 print("No data for visibility for " + str(month) + "/" + str(day) + "/" + str(year) + " Hour " + str(y)) visibility.append(x) x = data.get('precipIntensity', "none") if (x == "none"): x = 0 print("No data for precipIntensity for " + str(month) + "/" + str(day) + "/" + str(year) + " Hour " + str(y)) precipIntensity.append(x) x = data.get('precipProbability', "none") if (x == "none"): x = 0 print("No data for precipProbability for " + str(month) + "/" + str(day) + "/" + str(year) + " Hour " + str(y)) precipProbability.append(x) # Write data to csv data = [] data.extend(windGust) data.extend(temperature) data.extend(dewPoint) data.extend(humidity) data.extend(apparentTemperature) data.extend(pressure) data.extend(windSpeed) data.extend(visibility) data.extend(precipIntensity) data.extend(precipProbability) data.append(day) data.append(month) data.append(outcome) writer.writerow(data) print("Success for " + str(month) + "/" + str(day) + "/" + str(year)) print(str(len(data)) + " data points")
def get_weather(): forecast = forecastio.load_forecast(weather_api, 42.3591473, -71.09677909999999) weather_now = forecast.currently().summary return weather_now
def insert_data_for_date(self, date): print("Adding weather for date: %s" % (date)) dt = datetime(year=date.year, day=date.day, month=date.month, hour=BEST_HOUR) nodes = models.Node.objects.filter(include_weather=True) forecasts = [] for node in nodes: print('adding weather for node %s' % node.name) latitude = node.latitude longitude = node.longitude future_dt = dt + timedelta(days=1) forecast = forecastio.load_forecast(api_key, latitude, longitude, time=future_dt) by_hour = forecast.hourly() for hour_block in by_hour.data: print(loader_utils.utc_to_eastern(hour_block.time)) print(hour_block.__dict__) eastern_dt = loader_utils.utc_to_eastern(hour_block.time) hour = eastern_dt.hour if hour == 0: eastern_dt = eastern_dt - timedelta(days=1) hour = 24 print(dt) print(future_dt) print(eastern_dt) w = models.WeatherForecast( prediction_made_dt=dt, predicted_hour=hour, predicted_date=eastern_dt, latitude=latitude, longitude=longitude, cloud_cover=hour_block.cloudCover if hasattr( hour_block, "cloudCover") else 0, apparent_temp=hour_block.apparentTemperature, pressure=hour_block.pressure if hasattr( hour_block, "pressure") else 0, visibility=hour_block.visibility if hasattr( hour_block, "visibility") else 0, summary=hour_block.summary, temperature=hour_block.temperature, dew_point=hour_block.dewPoint if hasattr( hour_block, "dewPoint") else 0, humidity=hour_block.humidity if hasattr( hour_block, "humidity") else 0, ozone=hour_block.ozone if hasattr(hour_block, "ozone") else 0, wind_speed=hour_block.windspeed if hasattr( hour_block, "windspeed") else 0, wind_bearing=hour_block.windBearing if hasattr( hour_block, "windBearing") else 0, precip_intensity=hour_block.precipIntensity if hasattr( hour_block, "precipIntensity") else 0, precip_probability=hour_block.precipProbability if hasattr( hour_block, "precipProbability") else 0, ) forecasts.append(w) models.WeatherForecast.objects.bulk_create(forecasts)
import forecastio import requests import json API_KEY = "f5af7c9d5dcae926c4e5fcf75ea35dc6" send_url = "http://ip-api.com/json" r = requests.get(send_url) j = json.loads(r.text) latitude = j['lat'] longitude = j['lon'] print("current latitude, longitude is ", latitude, longitude) forecast = forecastio.load_forecast(API_KEY, latitude, longitude) #print(forecast) #j = json.loads(forecast.text) datapoint = forecast.currently() print(datapoint.summary) print(datapoint.temperature) print(datapoint.precipProbability)
def assistant(command): "if statements for executing commands" if 'open' in command: if 'C drive' in command: os.startfile('C:\\') say('Done!') if 'D drive' in command: os.startfile('D:\\') say('Done!') if 'quora' in command: webbrowser.open('www.quora.com') say('Done!') if 'facebook' in command: webbrowser.open('www.facebook.com') say('Done!') if '.com' in command: sf = re.split('\\bopen \\b', command)[-1] f = sf.replace(' ', '') greet = 'I have opened ' + f say(greet) webbrowser.open('www.' + f) else: sf = re.split('\\bopen\\b', command)[-1] greet = 'I have opened ' + sf say(greet) os.system('start' + sf) elif 'quit' in command: exit() elif "time" in command: say(ctime()) elif 'what up' in command: say('Just doing my thing') elif 'joke' in command: res = requests.get('https://icanhazdadjoke.com/', headers={"Accept": "application/json"}) if res.status_code == requests.codes.ok: say(str(res.json()['joke'])) else: say('oops!I ran out of jokes') elif 'weather' in command: forecast = forecastio.load_forecast(wapi_key, lat, lng) byHour = forecast.hourly() say(byHour.summary) elif "where is" in command: data = re.split('\\bis \\b', command)[-1] l2 = data location = data.replace(' ', '+') mixer.music.load('blank.mp3') say("Hold on, I will show you where " + l2 + " is.") webbrowser.open('https://www.google.nl/maps/place/' + location + '/&') time.sleep(4) else: response = chatbot.get_response(command) answer = str(response) say(answer)
def _get_forecast_io(self): return forecastio.load_forecast(self.api_key, self.lat, self.lng, units=self.units)
import forecastio from locationutil import location_to_latlong api_key = "" latlong = location_to_latlong('erie, colorado') forecast = forecastio.load_forecast(api_key, latlong[0], latlong[1]) print("===========Currently Data=========") print(forecast.currently()) print("===========Hourly Data=========") by_hour = forecast.hourly() print("Hourly Summary: %s" % by_hour.summary) for hourly_data_point in by_hour.data: print(hourly_data_point) print("===========Daily Data=========") by_day = forecast.daily() print("Daily Summary: %s" % (by_day.summary)) for daily_data_point in by_day.data: print(daily_data_point)
def updateWeather(self): ''' icon: clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night *precipProbability: 0 to 1 **precipType: rain, snow, sleet temperature: float apparentTemperature: feels like (float) *windSpeed: float **windBearing: 0 = True North -> clockwise cloudCover: 0 to 1 humidity: 0 to 1 Table: hourlyWeather Columns: date icon temperature apparentTemperature windSpeed windBearing cloudCover humidity precipProbability precipType Table: dailyWeather Columns: date tempMin tempMinTime tempMax tempMaxTime moonPhase ''' if self.config['weather_enabled']: try: if (datetime.now() - self.lastWeatherUpdate).seconds > 3600: self.lastWeatherUpdate = datetime.now() #timezone offset for weather forecast utcDelta = (datetime.now() - datetime.utcnow()) utcDelta = timedelta( utcDelta.days, utcDelta.seconds + int(utcDelta.microseconds / 500000), 0) forecast = forecastio.load_forecast( self.config['api_key'], self.config['latitude'], self.config['longitude'], units=("us" if self.config['units'] == 'F' else "si")) hourly = forecast.hourly() hours = [] for data in hourly.data: t = data.time + utcDelta precipType = data.precipType if data.precipProbability else "N/A" windBearing = data.windBearing if data.windSpeed else "N/A" hours.append( (t, data.icon, data.temperature, data.apparentTemperature, data.windSpeed, windBearing, data.cloudCover, data.humidity, data.precipProbability, precipType, data.uvIndex)) # keep weather data for a month self.logsCursor.execute( "DELETE FROM hourlyWeather where date NOT IN (SELECT date from hourlyWeather ORDER BY date DESC LIMIT 750)" ) self.logsCursor.executemany( "INSERT OR REPLACE INTO hourlyWeather VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", hours) self.logsConn.commit() daily = forecast.daily() days = [] for data in daily.data: alerts = "" for alert in forecast.alerts(): if data.time.date() <= datetime.fromtimestamp( alert.expires).date(): alerts += "<span class=\"alertTitle\">{0}</span> \ <p class=\"alertBody\">{1}</p>".format( alert.title, alert.description) alerts = "<div id=\"weatherAlerts\">" + alerts + "</div>" if alerts else None for entry in [ 'sunriseTime', 'sunsetTime', 'temperatureMinTime', 'temperatureMaxTime' ]: data.d[entry] = data.d.get(entry, None) if data.d[entry]: data.d[entry] = datetime.fromtimestamp( data.d[entry]) days.append( (data.time.date(), data.d.get('icon', None), data.d.get('summary', None), data.d.get('temperatureMin', None), data.d['temperatureMinTime'], data.d.get('temperatureMax', None), data.d['temperatureMaxTime'], data.d['sunriseTime'], data.d['sunsetTime'], data.d.get('moonPhase', None), data.d.get('precipProbability', None), data.d.get('windSpeed', None), data.d.get('windBearing', None), data.d.get('humidity', None), data.d.get('ozone', None), data.d.get('pressure', None), data.d.get('cloudCover', None), data.d.get('visibility', None), alerts)) self.logsCursor.execute( "DELETE FROM hourlyWeather where date NOT IN (SELECT date from hourlyWeather ORDER BY date DESC LIMIT 400)" ) self.logsCursor.executemany( "INSERT OR REPLACE INTO dailyWeather VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", days) self.logsConn.commit() except: print("Error while getting weather info:", sys.exc_info()[0])
def weatherFormat(name, lat, lng): forecast = forecastio.load_forecast(api_key, lat, lng) forecast_now = forecast.currently() forecast_today = forecast.daily().data[0] out = [] data = [] out.append(name) data.append(forecast_now.summary) hi = tempColor(forecast_today.temperatureMax) lo = tempColor(forecast_today.temperatureMin) data.append('Hi: {:s} °F | Lo: {:s} °F'.format(hi, lo)) temp = forecast_now.temperature feels_like = forecast_now.apparentTemperature temp_str = tempColor(temp) feels_like_str = tempColor(feels_like) if (abs(temp - feels_like) > 1.0): data.append('Currently: {:s} ({:s}) °F'.format(temp_str, feels_like_str)) else: data.append('Currently: {:s} °F'.format(temp_str)) try: wind_bearing_str = angleArrow(forecast_now.windBearing) except: wind_bearing_str = '' wind_speed_str = windColor(forecast_now.windSpeed) data.append('{:s} {:s} mph'.format(wind_bearing_str, wind_speed_str)) data.append('{:.1f} mi.'.format(forecast_now.visibility)) try: precip_accumulation = forecast_now.precipAccumulation except: precip_accumulation = 0.0 data.append('{:.1f} in. | {:.0f}%'.format( precip_accumulation, forecast_now.precipProbability * 100.0)) icon = weather_graphic.get(forecast_now.icon, weather_graphic['unknown']) icon_padded_width = 15 icon_default_width = len(ansi_escape.sub('', icon[0])) for i in range(max(len(icon), len(data))): if (i >= len(icon)): data[i] = ' ' * icon_padded_width + data[i].strip() elif (i >= len(data)): data.append(icon[i]) else: data[i] = icon[i] + \ (icon_padded_width - icon_default_width) * ' ' + data[i] for line in data: out.append(line) return out
def test_without_time(self): forecast = forecastio.load_forecast(self.api_key, self.lat, self.lng) self.assertEqual(forecast.response.status_code, 200)
del datatemp[0] del datatemp[len(datatemp) - 1] del datahumid[0] del datahumid[len(datahumid) - 1] # We should now look at the data and remove any highs or lows possibly # TODO: some basic data manipulations capture_time = time.strftime('%Y-%m-%d %H:%M:%S') datatemp = np.array(map(float, datatemp)) datahumid = np.array(map(float, datahumid)) insidetemp = round(Decimal(np.average(datatemp)), 1) insidehumid = round(Decimal(np.average(datahumid)), 1) forecast = forecastio.load_forecast(APIKEY, LAT, LOG) curforecast = forecast.currently() forecast_icon = curforecast.icon forecast_outside_temp = convertFtoC(curforecast.temperature) forecast_outside_humid = convertHumidPercent(curforecast.humidity) forecast_outside_apparent_temp = convertFtoC( curforecast.apparentTemperature) # Let's insert our data in mysql # Support multiple databases ?
def do(self, entities): forecast = forecastio.load_forecast(os.environ['FORECASTIO_KEY'], entities['coords'].latitude, entities['coords'].longitude) entities['weather'] = [forecast.hourly().summary] return entities
import forecastio import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt api_key = "cb91f1d7b02d54aa27438663b43dee23" lat = 37.967819 lng = 112.87718 forecast = forecastio.load_forecast(api_key, lat, lng) byHour = forecast.hourly() #print(byHour.summary) #print(byHour.icon) a = [] for hourlyData in byHour.data: a.append(hourlyData.temperature) #print(hourlyData.temperature) x = list(range(49)) y = a plt.plot(x,y) plt.xlabel('hour') plt.ylabel('Celsius') plt.title('The temperature in the next 48 hours from now') plt.yticks([15, 19, 23, 27, 31]) plt.grid(True) #plt.show() plt.savefig("./Figure_1.png")
def main(): api_key = "YOUR_FORECAST.IO_API_KEY" lat = 51.477 lng = 0.0000 forecast = forecastio.load_forecast(api_key, lat, lng) by_day = forecast.daily() # Open SVG to process output = codecs.open('weather-script-preprocess.svg', 'r', encoding='utf-8').read() # Insert icons and temperatures output = output.replace('ICON_ONE', by_day.data[0].icon).replace( 'ICON_TWO', by_day.data[1].icon).replace('ICON_THREE', by_day.data[2].icon).replace( 'ICON_FOUR', by_day.data[3].icon) output = output.replace( 'HIGH_ONE', str(int(round(by_day.data[0].temperatureMax)))).replace( 'HIGH_TWO', str(int(round(by_day.data[1].temperatureMax)))).replace( 'HIGH_THREE', str(int(round(by_day.data[2].temperatureMax)))).replace( 'HIGH_FOUR', str(int(round(by_day.data[3].temperatureMax)))) output = output.replace( 'LOW_ONE', str(int(round(by_day.data[0].temperatureMin)))).replace( 'LOW_TWO', str(int(round(by_day.data[1].temperatureMin)))).replace( 'LOW_THREE', str(int(round(by_day.data[2].temperatureMin)))).replace( 'LOW_FOUR', str(int(round(by_day.data[3].temperatureMin)))) #insert summary of day text summary = textwrap.wrap(forecast.hourly().summary, 55) wrappedsummary = summary[0] # the pre-process svg file has space for three lines of text. ANy more and we cut it off if len(summary) > 1: wrappedsummary = wrappedsummary + '<tspan x="25" dy="25">' + summary[ 1] + '</tspan>' if len(summary) > 2: wrappedsummary = wrappedsummary + '<tspan x="25" dy="25">' + summary[ 2] + '</tspan>' output = output.replace('TODAY_SUMMARY', wrappedsummary) # Insert days of week output = output.replace('DAY_THREE', by_day.data[2].time.strftime('%A')).replace( 'DAY_FOUR', by_day.data[3].time.strftime('%A')) #Insert timestamp output = output.replace('DATE_TIME', strftime("%H:%M %d/%m", gmtime())) # Write output codecs.open('weather-script-output.svg', 'w', encoding='utf-8').write(output)
def get_weather(lat, lng): forecast = forecastio.load_forecast(api_key, lat, lng) byHour = forecast.hourly() return byHour.data
def forecast(lat=37.512, lng=126.954): forecast = forecastio.load_forecast(FORECAST_TOKEN, lat, lng) byHourly = forecast.hourly() return byHourly.summary