Some example python code to fetch weather forecasts…

July 8, 2014 | My Projects, Python, Web Programming | By: Mark VandeWettering

Need to get some weather information? The website forecast.io has a nice web based service you can use up to one thousand times a day for free. I was thinking of using it for an automated sprinkler application, but just to test it, I wrote this simple chunk of python to try it out. To use it yourself, you’ll need to get your own API key and modify it to use your own latitude and longitude. It’s not that amazing, but you might find it of use.

[sourcecode lang=”python”]
#!/usr/bin/env python

# __ _
# / _|___ _ _ ___ __ __ _ __| |_
# | _/ _ \ ‘_/ -_) _/ _` (_-< _|
# |_| \___/_| \___\__\__,_/__/\__|
#
# A python program which used some publically available
# web apis to find out what the forecast will be.
#

# You’ll need an API key below… you get 1000 requests per day for free.
# Go to forecast.io and sign up.

API="PUT_YOUR_OWN_API_KEY_HERE"
URL="https://api.forecast.io/forecast/"

# Your latitude and longitude belong here, I use SF for example
LAT= 37.7833
LNG=-122.4167

directions = ["N", "NNE", "ENE", "E", "ESE", "SSE", "S", "SSW", "WSW", "W", "WNW", "NNW"]

def bearing_to_direction(bearing):
d = 360. / 12.
return directions[int((bearing+d/2)/d)]

import sys
import os
import time
import optparse
import json

import urllib2

now = time.time()
cached = False

if os.path.exists("WEATHER.cache"):
f = open("WEATHER.cache")
parsed = json.loads(f.read())
f.close()
if now – parsed["currently"]["time"] < 900:
cached = True

if cached:
print "::: Using cached data…"
else:
print "::: Reloading cache…"
req = urllib2.Request(URL+API+"/"+("%f,%f"%(LAT,LNG)))
response = urllib2.urlopen(req)
parsed = json.loads(response.read())
f = open("WEATHER.cache", "w")
f.write(json.dumps(parsed, indent=4, sort_keys=True))
f.close() ;

c = parsed["currently"]
print ":::", time.strftime("%F %T", time.localtime(c["time"]))
print "::: Conditions:", c["summary"]
print "::: Temperature:", ("%.1f" % c["temperature"])+u"\u00B0"
print "::: Dew Point:", ("%.1f" % c["dewPoint"])+u"\u00B0"
print "::: Humidity:", ("%4.1f%%" % (c["humidity"]*100.))
print "::: Wind:", int(round(c["windSpeed"])), "mph", bearing_to_direction(c["windBearing"])

d = parsed["daily"]["data"][0]
print "::: High:", ("%.1f" % d["temperatureMax"])+u"\u00B0"
print "::: Low:", ("%.1f" % d["temperatureMin"])+u"\u00B0"

d = parsed["hourly"]["data"]

for x in d[:12]:
print time.strftime("\t%H:%M", time.localtime(x["time"])), x["summary"], ("%.1f" % x["temperature"])+u"\u00B0"
[/sourcecode]

Comments

Comment from Oliver
Time 5/12/2016 at 1:22 pm

Hello Mark

thanks a lot for this great script. I started playing around with my raspberry, trying to set up a kind of surveillance system , including the weather stuff. I copied your script, and it works perfectly well. Great Job – Thanks.

Cheers
Oliver

Comment from Johan du Plessis
Time 6/4/2016 at 2:51 am

Hey. Thank for this, was looking for the bearing calculation.

When using a bearing of 355 you get index our of range because the calculation equates to 12, and the directions list accepts 0 – 11. Ended up just subtracting one `return directions[int((bearing + d / 2) / d – 1)]`

Thanks for the example 🙂