Search code examples
pythonpython-3.xpython-holidays

How can i list all holidays' date for each country using holidays module in python?


I am trying to find holidays' date with holidays package in python for many countries but, instead of writing one by one like this:

import holidays
for date in holidays.UnitedKingdom(years=2011).items():
    print(str(date[0]))

for date in holidays.Argentina(years=2011).items():
    print(str(date[0]))

I am trying to do this with a function like this:

for i in dir(holidays):
    for j in range(2010,2016):
        holidays.i(years=2011).keys()

I know that with loop every country's name is a string but I want to implement it as a loop, if you have any advice or suggestion please share with me. thank you.


Solution

  • Firstly: pip show holidays and then copy the location into the locationVariable

    import holidays
    import os
    locationVariable = ""
    countries = [name.split(".py")[0].replace("_"," ") for name in os.listdir(locationVariable+"holidays/countries/") if name.endswith(".py") and  not name.startswith("__")]
    
    print("List of countries are : " + str(len(countries)))
    
    for i in countries:
        for j in range(2010,2021):
            try:
                print(getattr(holidays,i.title().replace(" ",""))(years=j).keys())
            except:
                print("unable to iterate "+i.title().replace(" ",""))
                break
    

    seems like the formatting of the name is inconsistent(for Hongkong), please and use.

    Make sure to mark is answered if helpfull.