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 (
end) and GPS
# 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. The
Pointclass 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:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.