To get historical weather data in Python, install the Meteostat library using pip install meteostat
or run !pip install meteostat
with the exclamation mark prefix !
in a Jupyter Notebook.
If you haven’t already, also install the Matplotlib library using pip install matplotlib
.
Then, copy the following code into your programming environment and change the highlighted lines to set your own timeframe (start
, end
) and GPS location
:
# Import Meteostat library and dependencies from datetime import datetime import matplotlib.pyplot as plt from meteostat import Point, Daily # Set time period start = datetime(2023, 1, 1) end = datetime(2023, 12, 31) # Create Point for Stuttgart, Germany location = Point(48.787399767583295, 9.205803269767616) # Get daily data for 2023 data = Daily(location, start, end) data = data.fetch() # Plot line chart including average, minimum and maximum temperature data.plot(y=['tavg', 'tmin', 'tmax']) plt.show()
This code fetches and visualizes the average, minimum, and maximum temperatures for Stuttgart, Germany, for the entire year of 2023 using the Meteostat library.
Here’s the output:
Here are the three highlighted lines:
start = datetime(2023, 1, 1)
: This sets the start date to January 1, 2023.end = datetime(2023, 12, 31)
: This sets the end date to December 31, 2023. Together, these lines define the time period for which we want to fetch the weather data.location = Point(48.787399767583295, 9.205803269767616)
: This creates a geographical point for Stuttgart, Germany using its latitude and longitude GPS coordinates. ThePoint
class is used to represent a specific location on Earth.
You can use Google Maps to copy the GPS location of your desired location:
You can try it yourself in the interactive Jupyter notebook (Google Colab):
If you want to become a Python master, get free cheat sheets, and coding books, check out the free Finxter email academy with 150,000 coders like you: