How To Detect If A Date Is A Public Holiday In Python 3


Determining the current date is a public holiday can be tricky when holidays change and it of course changes from country to country. From system time of servers & machines running to timestamps for tracking the transactions and events in e-commerce platforms, the date and time play a major role. There are a variety of use cases related to manipulating date and time that can be solved using the inbuilt datetime module in Python3, such as

  • Finding if a given year is a leap year or an ordinary year
  • Finding the number of days between the two mentioned dates
  • Convert between different date or time formats

What if you were to check if a given date is a public holiday? There isn’t any specific formula or logic to determine that, do we? Holidays can be pre-defined or uncalled for.

Here, we will be exploring the two ways to detect if a date is a holiday or not.

Checking For Public Holiday With Holidays Module

Although Python3 doesn’t provide any modules to detect if a date is a holiday or not, there are some of the external modules that help in detecting this. One of those modules is Holidays.

In your terminal, type in the following to get the module installed.

sudo pip3 install holidays
Module Installation Demo – holidays

Now that our module is ready, let’s understand a bit about what the module and what it is capable of. Have a look at the following code snippet.

'''
Snippet to check if a given date is a holiday
'''

from datetime import date                                           # Step 1
import holidays

us_holidays = holidays.UnitedStates()                               # Step 2

input_date = input("Enter the date as YYYY-MM-DD: ")                # Step 3

holiday_name = us_holidays .get(input_date)                         # Step 4

if holiday_name != None: 
    output = "{} is a US Holiday - It's {}".format(input_date, holiday_name)
else:
    output = "{} is not a US Holiday".format(input_date)
                                                                    # Step 5
print (output)

In the above snippet,

  • Step 1: Imports the required modules
  • Step 2: Initializes the us_holidays object, so that the corresponding get function can be invoked at step 3
  • Step 3: Gets dateinput from the user
  • Step 4: Invokes the get function of the holidays module. This returns the name of the holiday if the date is a holiday or returns None in case if it isn’t. This gets assigned to the variable – holiday_name.
  • Step 5: Based on the variable – holiday_name, using the if clause the string formatting is done. Can you make this if clause even leaner? Read this article to know about the One line if else statements.

Here’s what the output looks like.

Checking For Holidays With API Call to Calendarific

The above method is suitable for simple projects; however, it can never be used to provide an enterprise-grade solution. Let’s say, you are building a web application for a holiday and travel startup, building an enterprise-grade application requires an enterprise-grade solution. If you haven’t noticed, the holidays module is pretty simple and if you consider state-wise or newly announced holidays, then this solution doesn’t simply cut for a large-scale application.

Enterprise requirements such as these can be satisfied by using external APIs such as Calendarific which provides the API as a service for such applications to consume. They keep updating the holidays of states and countries constantly, and the applications may consume these APIs. Of course, enterprise solutions don’t always come free, but the developer account has a limit of 1000API requests per month.

Locate to https://calendarific.com/ on your favorite browser and follow the steps as shown in the following images to get yourself a free account and an API key for this exercise.

Step 1: Open Calendarific on your favorite browser
Step 2: Signup for a free account
Step 3: Login to your account
Step 4: Copy the API Key

Understanding the Calendarific REST API

Before we could dive into using the API KEY, get yourself a REST API client – Insomnia or Postman. We are about to test our API key if we are able to retrieve the holiday information. Plugin the following URL by replacing [APIKEY] text with your API KEY received from above on your REST client.

https://calendarific.com/api/v2/holidays?api_key=[APIKEY]&country=us-ny&type=national&year=2020&month=1&day=1

In the above URL:

  • https://calendarific.com/api/v2 is the API Base URL
  • /holidays is the API route
  • api_key, country, type, year, month, day are URL Parameters
  • Each parameter has a value allocated to it with an = (equal sign)
  • Each parameter and value pair is split by an & (ampersand)

For the above API call, the following response will be received; the value corresponding to the code key under the meta tag as ‘200’ corresponds to a successful response.

{
  "meta": {
    "code": 200
  },
  "response": {
    "holidays": [
      {
        "name": "New Year's Day",
        "description": "New Year's Day is the first day of the Gregorian calendar, which is widely used in many countries such as the USA.",
        "country": {
          "id": "us",
          "name": "United States"
        },
        "date": {
          "iso": "2020-01-01",
          "datetime": {
            "year": 2020,
            "month": 1,
            "day": 1
          }
        },
        "type": [
          "National holiday"
        ],
        "locations": "All",
        "states": "All"
      }
    ]
  }
}

The REST API call has returned some useful info about the National holiday on the 1st of January. Let’s see if it’s able to detect for the 2nd of January. Plugin the following URL again by replacing the text [APIKEY] with your API Key.

https://calendarific.com/api/v2/holidays?api_key=[APIKEY]&country=us-ny&type=national&year=2020&month=1&day=2

The above URL should be returning a response similar to below.

{
   "meta": {
     "code": 200
   },
   "response": {
     "holidays": []
   }
 }

Indeed, the 2nd of January is not a public holiday and hence, the holidays list inside the response nested JSON key turns out to be an empty list.

Now we know that our API works very well, it is now time to incorporate Calendarific REST API into our Python code. We will be using the requests module in order to make this happen. Here’s how it is done.

'''
Snippet to check if a given date is a holiday using an external API - Calendarific
'''

import requests                                                     # Step 1

api_key   = '[APIKEY]'                                              # Step 2
base_url  = 'https://calendarific.com/api/v2'
api_route = '/holidays'

location  = input("Enter Country & State code - E.g.: us-ny: ")
date_inpt = input("Enter the date as YYYY-MM-DD: ")                 # Step 3
y, m, d = date_inpt.split('-')
 
full_url = '{}{}?api_key={}&country={}&type=national&year={}&month={}&day={}'\
                .format(base_url, api_route, api_key, location, str(int(y)), str(int(m)), str(int(d)))                                           # Step 4

response = requests.get(full_url).json()                            # Step 5

if response['response']['holidays'] != []:
    print ("{} is a holiday - {}".format(date_inpt, response['response']['holidays'][0]['name']))
else:                                                               # Step 6
    print ("{} is not a holiday".format(date_inpt))

In the above snippet,

  • Step 1: Import requests module – you will be needing this module to invoke the REST API.
  • Step 2: Replace ‘[APIKEY]’ with your own API key from Calendarific
  • Step 3: The user inputs the corresponding location and date for which the holiday needs to be detected
  • Step 4: String formatting in order to frame the URL
  • Step 5: Invoke the API and convert the response to a JSON; i.e.) a dictionary
  • Step 6: If clause checks for the presence of an empty list or with a returned response.

Here’s what the output looks like.

And there you have it, a working example for detecting if a given date is a holiday using an external API.

Summary

From an overall perspective, there could be multiple ways to solve a given problem, and here, we have portrayed two of those ways in detecting if a given date is a holiday or not. One is a straight forward out-of-the-box solution and the other one is an enterprise-ready solution, which one would you choose?

Subscribe to our newsletter

Get new tips in your inbox automatically. Subscribe to our newsletter!

Charles White

I'm a big believer in the value of learning to code and learning to code is something that everyone should learn these days. Here are a collection of things i've learned over the years..

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Content