Pages

Saturday, 9 June 2018

Get the weather using Python

I recently spent a hour or so hacking a lucky cat so that it would only wave when it was sunny.
It did this by pulling the weather data from Open Weather Map using the Python module pyowm.

1. Sign up for a free API key in Open Weather Map.

2. Install the pyown Python module, open a Terminal or Command Prompt and run:

Windows
pip install pyown

Raspberry Pi / Linux
sudo pip3 install pyown

MacOS
pip3 install pyown

3. Create a Python program using the following code, inserting your API key:
import pyowm

owm = pyowm.OWM('put api key here')

observation = owm.weather_at_place('Cambridge,GB')
w = observation.get_weather()

clouds = w.get_clouds()
wind = w.get_wind()
humidity = w.get_humidity()
temp = w.get_temperature('celsius')

print("{}, {}, {}, {}".format(clouds, wind, humidity, temp)

Note - it can take up to 60 minutes for your API key to be activated.

There is a lot more information which can be pulled back - have a look at the weather module documentation for more details.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.