Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick and dirty forecast.io wrapper.
import datetime
import pytz
import requests
import time as time_mod
FORECAST_TEMPLATE = 'https://api.forecast.io/forecast/{apikey}/{latitude},{longitude}{time}{si}'
class Forecast(object):
data = None
timezone = None
def __init__(self, apikey):
self.apikey = apikey
def get(self, latitude, longitude, time=None, si=False):
if time:
time = int(time_mod.mktime(time.timetuple()))
url = FORECAST_TEMPLATE.format(
apikey=self.apikey,
latitude=latitude,
longitude=longitude,
time=',{}'.format(time) if time else '',
si='?{}'.format(si) if si else ''
)
request = requests.get(url)
self.data = request.json()
if 'timezone' in self.data:
self.timezone = pytz.timezone(self.data['timezone'])
self.data = self.fix_timestamps(self.data)
return self.data
def timestamp_to_datetime(self, timestamp):
return datetime.datetime.fromtimestamp(int(timestamp)).replace(tzinfo=self.timezone)
def fix_timestamps(self, data):
if isinstance(data, list):
values = []
for item in data:
value = self.fix_timestamps(item)
values.append(value)
return values
elif isinstance(data, dict):
values = {}
for key, value in data.items():
if type(value) in [dict, list]:
value = self.fix_timestamps(value)
elif key == 'time' or key.endswith('Time'):
value = self.timestamp_to_datetime(value)
values[key] = value
return values
else:
values = data
return values
@property
def current(self):
if 'currently' in self.data:
return self.data['currently']
else:
return None
@property
def daily(self):
if 'daily' in self.data:
return self.data['daily']
else:
return None
@property
def hourly(self):
if 'hourly' in self.data:
return self.data['hourly']
else:
return None
@property
def minutely(self):
if 'minutely' in self.data:
return self.data['minutely']
else:
return None
from datetime import datetime
from requests_forecast import Forecast
def main():
forecast = Forecast('YOUR-API-KEY')
data = forecast.get(
latitude=38.9717,
longitude=-95.235,
#time=datetime(year=2013, month=9, day=18)
)
print 'current.temperature: {}'.format(forecast.current['temperature'])
print 'current.cloudCover: {}'.format(forecast.current['cloudCover'])
print 'current.humidity: {}'.format(forecast.current['humidity'])
print 'current.icon: {}'.format(forecast.current['icon'])
print 'current.precipIntensity: {}'.format(forecast.current.get('precipIntensity'))
print 'current.pressure: {}'.format(forecast.current['pressure'])
#print 'current.latitude: {}'.format(forecast.current['latitude'])
#print 'current.longitude: {}'.format(forecast.current['longitude'])
print 'current.summary: {}'.format(forecast.current['summary'])
print 'current.time: {}'.format(forecast.current['time'])
print 'current.visibility: {}'.format(forecast.current['visibility'])
print 'current.windBearing: {}'.format(forecast.current['windBearing'])
print 'current.windSpeed: {}'.format(forecast.current['windSpeed'])
print 'current: {}'.format(forecast.current)
print '-' * 20
#{u'temperature': 47.68, u'humidity': 0.58, u'cloudCover': 0.63, u'summary': u'Mostly Cloudy',
#u'pressure': 986.74, u'windSpeed': 11.12, u'visibility': 9.3, u'time': 1364422970, u'windBearing': 102, u'precipIntensity': 0, u'icon': u'partly-cloudy-day'}
print 'daily: {}'.format(len(forecast.daily['data']))
print 'hourly: {}'.format(len(forecast.hourly['data']))
#print 'minutely: {}'.format(len(forecast.minutely['data']))
#pprint(data)
if __name__ == '__main__':
main()
@wimsy

This comment has been minimized.

Copy link

commented Apr 12, 2013

Hey, this was really helpful. Thanks! I forked and updated it a bit for the latest API changes because I needed to use features like exclude. Not promising it's a good implementation, but it worked for me. Check it out.

@tctippen

This comment has been minimized.

Copy link

commented Apr 14, 2013

Any hints on how to use this? I'm relatively new to coding and I'm trying to use this for a project.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.