Holidays library in Python: Examples
This Python tutorial talks about the holidays library. This library helps us find out efficiently whether a specific date is a holiday or not. Install it using the following command.
pip install holidays
We will read more about this further in this tutorial.
Holidays library in Python: Syntax
The syntax for the base class is given below:
class holidays.HolidayBase(years=, expand=True, observed=True, prov=None, state=None)
Now let’s understand the parameters.
This specifies an iterable list of integers and should be pre-generated by the holiday object. We use this only when expand parameter is set to False. The default value for years parameter is .
This is a boolean parameter to specify whether the holidays should be appended or not in new years to holidays object. The default value is True.
This is also a boolean parameter. When it is set to True, it will include the observed day of a holiday that falls on a weekend, when appropriate. Its default value is True.
A string that specifies a province.
A string that specifies a state.
Methods in the holidays library
Here are few methods listed that are used in this library.
get(key, default = None): This method returns the name of the holiday on the given date specified in with key parameter. If there are multiple holidays for the same day, the names are separated by commas.
getlist(key): This method returns a list of holiday names.
pop(key, default = None): This method removes the key from the holidays object.
Now let’s see some usage of these functions.
holidays library: Usage
The below program checks whether the given date is a holiday or not. See the code.
from datetime import time import holidays ind_holidays = holidays.India() if '15-08-2020' in ind_holidays: print(ind_holidays.get('15-08-2020')) else: print("Not a holiday")
The program prints “Not a holiday” if no holiday falls on the given date.
When we use get_list() methods, the return type is a list. See the code given below.
from datetime import time import holidays ind_holidays = holidays.India() if '15-08-2020' in ind_holidays: print(ind_holidays.get_list('15-08-2020')) else: print("Not a holiday")
Also read: Calendar module in Python