This article was published as a part of the Data Science Blogathon.
PyOWM (Python OpenWeatherMap) is a Python wrapper for the OpenWeatherMap API that allows developers to easily access a wide range of weather data for various locations. This includes current weather conditions, such as temperature, humidity, wind speed, and direction, as well as forecasts and historical data. This data can be retrieved for locations around the world, making it a useful tool for a wide range of applications.
Source: Open Weather
In addition to providing access to a wide range of weather data, PyOWM is also easy to use and well-documented. It has a clear and concise API, with detailed documentation and examples to help developers get started quickly. This makes it a good choice for developers who need to retrieve and use weather data in their projects but may not have much experience working with APIs.
In this article, we will take a closer look at pyOWM and see how it can be used to retrieve weather data from the OpenWeatherMap API. We will cover the installation and setup of pyOWM, as well as some examples of how to use it to retrieve and work with weather data.
Before we can start using pyOWM, we need to install it. The easiest way to install pyOWM is using pip, the Python package manager. To install pyOWM, open a terminal and run the following command:
pip install pyowm
Once PYOWM is installed, you will need to sign up for an API key from the OpenWeatherMap website. This key is required to access the API and request weather data. Obtaining an API key is straightforward and only requires a valid email address.
Source: Open Weather API
After obtaining an API key, you will need to configure PYOWM to use it. This can be done by setting the OWM_API_KEY environment variable to your API key. For example, on Windows, you can set the environment variable using the following command:
set OWM_API_KEY=YOUR_API_KEY
On Linux or macOS, you can set the environment variable using the following command:
export OWM_API_KEY=YOUR_API_KEY
Once you set the OWM_API_KEY environment variable, you can start using PYOWM in your Python projects.
PyOWM provides several functions for making API requests and retrieving weather data. These functions can be imported from the pyOWM module, which is the main entry point for the package.
To get started, you will need to import the pyOWM module and create an instance of the OWM class. This class is responsible for managing your API key and making requests to the OpenWeatherMap API. You can create an instance of the OWM class by calling the OWM() constructor and passing it your API key as an argument.
import pyowm owm = pyowm.OWM(API_KEY)
With an instance of the OWM class, you can now use its various methods to make API requests and retrieve weather data.
Once we have an instance of the OWM class, we can use it to request the OpenWeatherMap API and retrieve current weather data for a specific location. To do this, we can use the weather_at_place() method of the WeatherManager class. This method takes a string representing the name of a city or location and returns a Weather object with data on the current weather conditions.
We will use the PyOWM library to retrieve and analyze weather data for Kolkata, India.
Here is an example of how to use the weather_at_place() method to retrieve current weather data:
import pyowm owm = pyowm.OWM('API_KEY') weather_mgr = owm.weather_manager() place = 'Kolkata, IN' observation = weather_mgr.weather_at_place(place)
The weather object contains various properties that contain the current weather data for the specified location. For example, we can access the temperature, humidity, and wind speed like this:
temperature = observation.weather.temperature("celsius")["temp"] humidity = observation.weather.humidity wind = observation.weather.wind() print(f'Temperature: {temperature}°C') print(f'Humidity: {humidity}%') print(f'Wind Speed: {wind["speed"]} m/s')
The output of current weather data
In addition to current weather data, pyOWM also allows us to retrieve forecast data for a specific location. To do this, we can use the forecast_at_place() method of the WeatherManager class, which takes a location string and an interval string as arguments. The interval argument specifies the time period for which you want to retrieve the forecast data and can be one of the following values: “3h” (3 hours), “9h” (9 hours), “12h” (12 hours), “24h” (24 hours), or “60h” (60 hours).
Here is an example of how to use the forecast_at_place() method with an interval argument to retrieve the forecast data for the next 24 hours:
forecast = weather_mgr.forecast_at_place(place, "24h")
The Forecast object contains a list of Weather objects, each representing the weather data for a specific time period in the forecast. We can access this list of Weather objects using the methods of the Forecast object.
For example, to print the temperature, humidity, and wind speed for each time period in the forecast, we can do the following:
forecast_list = forecast.get_forecast() for weather in forecast_list: temperature = weather.get_temperature('celsius') humidity = weather.get_humidity() wind = weather.get_wind() print(f'Temperature: {temperature}°C') print(f'Humidity: {humidity}%') print(f'Wind Speed: {wind["speed"]} m/s')
In addition to current and forecast data, pyOWM also allows us to retrieve historical weather data for a specific location and time period. To do this, we can use the weather_history_at_place() method, which takes a location string and a start and end date as arguments and returns a WeatherHistory object that contains the historical weather data for that location and time period.
For example, to retrieve the historical weather data for Kolkata for January 2021, we can do the following:
start_date = '2021-01-01' end_date = '2021-01-31' history = weather_mgr.weather_history_at_place(place, start_date, end_date)
The WeatherHistory object contains a list of Weather objects, each representing the weather data for a specific date in the time period. We can access this list of Weather objects using the get_weathers() method of the WeatherHistory object.
For example, to print the temperature, humidity, and wind speed for each day in the time period, we can do the following:
history = weather_mgr.weather_history_at_place(place, start_date, end_date) history_list = history.get_weathers() for weather in history_list: temperature = weather.get_temperature('celsius') humidity = weather.get_humidity() wind = weather.get_wind() print(f'Temperature: {temperature}°C') print(f'Humidity: {humidity}%') print(f'Wind Speed: {wind["speed"]} m/s')
To retrieve the latitude and longitude for a location, you can use the geocode() method of the GeocodingManager class. This method takes a location name or set of coordinates as an argument and returns a Location object containing the latitude and longitude of the location.
Here is an example of how to use the geocode() method to retrieve the latitude and longitude for Kolkata:
geo_mgr = owm.geocoding_manager() location = geo_mgr.geocode(place)
The location object returned by the geocode() method contains several attributes with data on the location, such as the name, latitude, and longitude. You can access these attributes by calling the corresponding method on the Location object.
name = location[0].name() latitude = location[0].lat() longitude = location[0].lon() print(f"Location: {name} ({latitude}, {longitude})")
Fetching Latitude & Longitude
In geocoding, the latitude and longitude coordinates are typically expressed in a format known as decimal degrees. In this format, the latitude and longitude values are expressed as a single floating point number, with the positive or negative sign indicating the hemisphere. For example, a latitude value of 40.7128 degrees north would be expressed as 40.7128, while a longitude value of 74.0060 degrees west would be expressed as -74.0060.
In contrast, the degree, minute, second (DMS) format commonly used in geography and navigation includes separate fields for the degree, minute, and second values, as well as a hemisphere indicator (N or S for latitude, E or W for longitude). For example, the same latitude value of 40.7128 degrees north would be expressed as 40° 42′ 46″ N in DMS format.
To retrieve the UV index data for a location using coordinates, you can use the uvindex_around_coords() method of the UVIndexManager class in the PyOWM library. This method takes a set of latitude and longitude coordinates as arguments, along with an optional date_time parameter, and returns a UVIndex object containing the UV index data for the location. Here is an example of how to use the uvindex_around_coords() method to retrieve the UV index data for the above location:
uv_mgr = owm.uvindex_manager() uv_index = uv_mgr.uvindex_around_coords(latitude, longitude) print(f"UV Index: {uv_index.value}") print(f"Exposure Risk: {uv_index.get_exposure_risk()}")
Fetching UV Index data
The UVIndex object has several attributes and methods that you can use to access the UV index data. For example, you can use the reference_time() method to retrieve the time that the UV index data was measured, or the reception_time() method to retrieve the time that the PyOWM client received the data.
Here is an example of how to use some of the attributes and methods of the UVIndex object:
print(f"Reference time: {uv_index.reference_time()}") print(f"Reception time: {uv_index.reception_time()}") print(f"UV index level: {uv_index.level()}")
This article shows how pyOWM can retrieve and work with weather data for OpenWeatherMap API. We have covered the installation and setup of pyOWM and some examples of how to use it to retrieve current weather data, forecast data, and historical data for a specific location. Here are some upshots about the pyOWM library:
The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.