Using the Open Weather Map API with Python

In this post, I am showing you how to use the freely available Open Weather Map API to retrieve hourly weather forecasts 48 hours into the future for a given place using Python without external packages.

Continue reading if you need an easy and flexible way to obtain weather data in your python application and you want to avoid using third-party dependencies for the task. You will use the free tier of the Open Weather Map API. The resulting weather data includes:

  • temperature
  • sunrise and sunset time
  • “feels like” temperature
  • pressure
  • humidity
  • wind speed
  • cloudiness

All the above data points are returned hourly for the next 48 hours in JSON format for free.

We will use Python to query the API without using any dependencies except for the requests and json packages so you can easily adapt it to suit your particular needs. Let’s get started!

Continue reading

Measure Code Execution Time Accurately in Python

Measuring code execution times is hard. Learn how to eliminate systematic and random measurement errors and obtain more reliable results.

We often need to measure how long a specific part of code takes to execute. Unfortunately, simply measuring the system time before and after a function call is not very robust and susceptible to systematic and random measurement errors. This is especially true for measuring very short intervals (< 100 milliseconds).

Systematic and Random Errors

So what is wrong with the following way of measuring?

time_start = time.perf_counter()
time_end = time.perf_counter()
execution_time = time_end - time_start

First, there is a systematic error: by invoking time.perf_counter(), an unknown amount of time is added to the execution time of my_function(). How much time? This depends on the OS, the particular implementation and other uncontrollable factors.

Second, there is a random error: the execution time of the call to my_function() will vary to a certain degree.

We can combat the random error by just performing multiple measurements and taking the average of those. However, it is much more challenging to remove the systematic error.

Continue reading