Photo by Nathan Anderson on Unsplash

Let’s Use Pandas & Requests to Grab UK Bank Holidays Dates with the gov.uk API

Umar Hussain
Ricoh Digital Services
2 min readDec 23, 2019

--

So, you have a custom internal calendar and someone forgot to add in bank holidays? or you noticed a spike in sales, an increase in web traffic and want to know if that date coincided with any key dates in the UK.

Well, thanks to a free government API we can easily grab this data in a JSON format and turn it into a nice looking pandas DataFrame.

Let's do that.

This will return a nested JSON like below:

print(python_dict)
{'england-and-wales': {'division': 'england-and-wales', 'events': [{'title': 'New Year’s Day', 'date': '2015-01-01', 'notes': '', 'bunting': True}, {'title': 'Good Friday', 'date': '2015-04-03', 'notes': '', 'bunting': False}, {'title': 'Easter Monday', 'date': '2015-04-06', 'notes': '', 'bunting': True},....

Now that we have the JSON safely nested inside a python dictionary type, lets loop over the relevant keys and add them to a new DataFrame.

which gives us a nice tabular DataFrame.

print(bank_hols.head(5))
title date notes bunting Country
0 New Year’s Day 2015-01-01 True england-and-wales
1 Good Friday 2015-04-03 False england-and-wales
2 Easter Monday 2015-04-06 True england-and-wales
3 Early May bank holiday 2015-05-04 True england-and-wales
4 Spring bank holiday 2015-05-25 True england-and-wales

We can then export the DataFrame to an Excel workbook or a CSV file (Comma Separated Values).

As a final test, let's find the last Scottish Bank Holiday & the next one.

we will first need to convert our date column into a proper DateTime column we can then use a simple formula

#current date = 22/12/2019
title St Andrew’s Day
date 2019-12-02
notes Substitute day
bunting True
Country scotland
Name: 98, dtype: object
title Christmas Day
date 2019-12-25
notes
bunting True
Country scotland
Name: 99, dtype: object

A few things to note, the data only goes far back as 2015 and the max date is the 28th of December 2021, you can read more about the Government APIs here: https://www.gov.uk/help/reuse-govuk-content

Full repo here

Happy Analysing!

--

--