Getting weather forecasts via openweathermap and python

This is a nerdy post. So unless you’re interested in python programming and getting weather information then this post is *not* for you.

Well here we go! I’m going to assume that you have python installed on your computer (or raspberry pi).

Firstly, you will need to install pyowm package.  You can do this with the command:

pip install pyowm
or
sudo pip install powm (if you are using a rpi)

Secondly,  in your python code, make sure you import the correct bits and pieces:

import pyowm
import json

Thirdly, what I was interested in was sending an email/text which aggregated the current weather conditions and added what to expect three hours later to that message.

owm = pyowm.OWM('INSERT-YOUR-API-KEY')
#Documentation is at https://pyowm.readthedocs.org/en/latest/pyowm.html
#Get you api key by signing up at http://openweathermap.org

#establish time constant
in3hours = pyowm.timeutils.next_three_hours()

#Retreive daily forecast
forecast = owm.daily_forecast('Castle Hill,au')

#Retrieve forecast at location in 3 hours
latertoday = forecast.get_weather_at(in3hours)
decoded_later = json.loads(latertoday.to_JSON()) #its easier to load it into JSON and decode it!
detailed_status_later = decoded_later['detailed_status'] #detailed status in 3 hours

# Search for current weather
observation = owm.weather_at_place('Castle Hill,au')
#observation = owm.weather_at_coords(-33.73, 150.998)
w = observation.get_weather()
decoded_w = json.loads(w.to_JSON())
detailed_status = decoded_w['detailed_status']

#Create String to Print
strMsg = 'Castle Hill: ' + detailed_status.title() + ' (later expect ' + detailed_status_later.title() + ') from ' + str(w.get_temperature('celsius')['temp_min']) + 'C to ' + str(w.get_temperature('celsius')['temp_max']) + 'C, ' + str(decoded_w['humidity']) + '% humidity & ' + str(decoded_w['clouds']) + '% cloud'
print(strMsg)

The output will look as follows:

Castle Hill: Broken Clouds (later expect Clear Sky) from 18.89C to 20.0C, 68% humidity & 75% cloud

It’s worth keeping in mind the documentation of pyowm and you can find that here

Advertisements