Using a weather api (forecast.io)

Sat 13 December 2014

Filed under Python

Kinda cool to get the weather just the way I need it

Moving along in discussing some of features of the little application I wrote.

I already got the IP and then found the longitude and latitude coordinates based on that IP.

The next step is to find the local weather for the current day. I tried several weather apis that were suggested by fellow HackerSchoolers. I found that the best and easiest to use is forecast.io. And it gave me the opportunity to work with json files.

First, I got myself a key from https://developer.forecast.io/. It's free.

And I also did pip install python-forecastio.

I already had my lat and lng so I passed those into the get_weather function as parameters.

from datetime import date
import requests

forecast_io_key = 'get your own key'
api_forecast_io = 'https://api.forecast.io/forecast/{}/{},{},{}'

def get_weather(lat, lng):
    date = '{}T12:00:00-0400'.format(datetime.date.today()) 
    lookup_url = api_forecast_io.format(forecast_io_key, lat, lng, date)
    json_response = requests.get(lookup_url).json()

    hourly_data = json_response[u'hourly'][u'data']

date: The api has optional parameter of time/date. This can be a datetime object. So first I import the datetime module. And import the requests module so I get the response from looking up a specific url. Read more about requests library.

The date/time must be either UNIX time or a string in this format. See comment below. I like to use the .format method to fill the string with variables. Read more about .format.

lookup_url: This is the url with the values filled in.

json_response: The response from the 'GET' request is a json file, which essentially is a list of dictionaries. In this case, a list of dictionaries of dictionaries. Seems like a threw myself right into a deep json file. Really had to sit on this file to understand it. Eventually I got it. See the json file below.

hourly_data: This is the json_response, using the hourly key to get the values of the data key. The value of the hourly key is several dictionaries – one for every hour.

Here's what just some of that json_response looks like. Look for the hourly key (about 5 lines in) and then for the data key (not far after the hourly key). NOTE: I put in the line breaks; before the data was running as one long line.

{"latitude":42.8964,"longitude":-78.8852,"timezone":"America/New_York","offset":-5,"currently":
{"time":1419436800,"summary":"Overcast","icon":"cloudy","precipIntensity":0.45,"precipProbability"
:0.09,"precipType":"rain","temperature":48.29,"apparentTemperature":43.71,"dewPoint":45.09,
"humidity":0.89,"windSpeed":10.58,"windBearing":155,"visibility":6.33,"cloudCover":1,
"pressure":1003.35,"ozone":294.97},"hourly":{"summary":"Light rain starting overnight.","icon":
"rain","data":[{"time":1419397200,"summary":"Overcast","icon":"cloudy","precipIntensity":0,
"precipProbability":0,"temperature":44.44,"apparentTemperature":40.14,"dewPoint":40.71,
"humidity":0.87,"windSpeed":7.67,"windBearing":146,"visibility":8.47,"cloudCover":1,"pressure":
1011.78,"ozone":300.77},{"time":1419400800,"summary":"Drizzle","icon":"rain","precipIntensity":
0.0081,"precipProbability":0.39,"precipType":"rain","temperature":44.19,"apparentTemperature":
39.28,"dewPoint":40.92,"humidity":0.88,"windSpeed":8.92,"windBearing":152,"visibility":8.14,
"cloudCover":1,"pressure":1011.55,"ozone":300.83},{"time":1419404400,"summary":"Drizzle","icon":
"rain","precipIntensity":0.0056,"precipProbability":0.11,"precipType":"rain","temperature":
44.24,"apparentTemperature":38.87,"dewPoint":41.4,"humidity":0.9,"windSpeed":10.07,
"windBearing":147,"visibility":7.96,"cloudCover":1,"pressure":1010.87,"ozone":300.48},

# and there is much more in that json file.

Lastly, I created a list of dictionaries of just the data I needed: for each hour, I need the temperature and windspeed and windchill. Using the temperature and windspeed, I could figure out the windchill. I found the windchill formula online.

import math  # used in the windchill formula

## continues from function above
hourly = []  

for hour in hourly_data:
    #find the windchill
    T = hour[u'temperature']
    V = hour[u'windSpeed']
    windchill = math.ceil(35.74 + (0.6215*T) - (35.75*(V**0.16)) + (0.4275*T*(V**0.16)))

    hour_dict= {
                'time': hour[u'time'],
                'temperature': hour[u'temperature'],
                'windspeed': hour[u'windSpeed'],
                'windchill': windchill}
    hourly_weather.append(hour_dict)

return hourly

hourly: I created a blank list hourly to which I will append a new dictionary for each hour.

Using a for loop - for each hour, I evaluate the windchill and create a new dictionary hour_dict and add keys/ values for time, temperature, windSpeed and windchill.

windchill: I found the windchill formula online. I get T and V for the temperature and windspeed. Those one letters are much shorter than the full name of the variable, much easier to type. (BTW, math.ceil(x) returns the smallest integer value greater than or equal to x. In other words, it always rounds up.)

Lastly, I append the new dictionary to the hourly list.

And walla! I have my list of dictionaries of weather info for each hour of the day. Next step would be to display it in a useful way. Maybe a different color based on the windchill. According to that chart, a windchill above 32F is comfortable for outdoor play and thus can be presented in GREEN. YELLOW is for temps between 13F and 32F. Anything lower than that is RED. And I'd probably also provide the data in celsius.

Done!

about the TIME FORMAT

TIME should either be a UNIX time (that is, seconds since midnight GMT on 1 Jan 1970) or a string formatted as follows: [YYYY]-[MM]-[DD]T[HH]:[MM]:[SS] (with an optional time zone formatted as Z for GMT time or {+,-}[HH][MM] for an offset in minutes or seconds). For the latter format, if no timezone is present, local time (at the provided latitude and longitude) is assumed. (This string format is a subset of ISO 8601 time. An as example, 2013-05-06T12:00:00-0400.)

MORE ABOUT THE PYTHON WRAPPER for FORECAST.IO

https://github.com/ZeevG/python-forecast.io


Comments


DeeKras.com © Dee Kras Powered by Pelican and Twitter Bootstrap. Icons by Font Awesome and Font Awesome More