Python Holidays library

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn about the holidays library. The holidays library will help to determine whether a particular is a holiday or not in different countries. We can only see the public holidays.

Let's install the module with the following command.

pip install holidays

After successfully installing the module follow the ways to see get the holidays information. see the holidays of India in the year 2020. You have to follow the below steps to get a complete list of holidays for India in 2020.

You can find the country codes for the holidays here..

  • Import the holidays' module.
  • Instantiate the holidays.India() and pass the keyword argument years as 2020.
  • It will return a dictionary of holidays with a date.
  • Iterate over the dictionary items and print them.

Example

Let's see the code to get all the holidays.

# importing holidays module
import holidays
# getting India holidays
india_holidays = holidays.India(years=2020)
# iterating over the holidays
for date, occasion in india_holidays.items():
   # printing date and occasion
   print(f'{date} - {occasion}')

Output

If you run the above code, then you will get the following result.

2020-01-14 - Makar Sankranti / Pongal
2020-01-26 - Republic Day
2020-08-15 - Independence Day
2020-10-02 - Gandhi Jayanti
2020-05-01 - Labour Day
2020-12-25 - Christmas

You can get the holidays of any available country. Change the code accordingly. Next, we will get the occasion of the holiday.

Example

# importing holidays module
import holidays
# getting India holidays
india_holidays = holidays.India()
# occasion on 15-08-2020
print(f"Occasion on 15-08-2020: {india_holidays.get('15-08-2020')}")

Output

If you run the above code, then you will get the following result.

Occasion on 15-08-2020: Independence Day

Let's see whether a particular day is holiday or not.

Example

# importing holidays module
import holidays
# getting India holidays
india_holidays = holidays.India()
# holiday date
date_one = '15-08-2020'
date_two = '16-08-2020'
print(f"Is it holiday on {date_one}: {india_holidays.get(date_one) != None}")
print(f"Is it holiday on {date_two}: {india_holidays.get(date_two) != None}")

Output

If you execute the above program, then you will get the following result.

Is it holiday on 15-08-2020: True
Is it holiday on 16-08-2020: False

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

raja
Published on 07-Jul-2020 12:11:14
Advertisements