Detecting a US Holiday

前端 未结 5 1592
醉酒成梦
醉酒成梦 2020-12-25 12:27

What\'s the simplest way to determine if a date is a U.S. bank holiday in Python? There seem to be various calendars and webservices listing holidays for various countries,

5条回答
  •  一向
    一向 (楼主)
    2020-12-25 13:07

    Use the holiday library in python.

    pip install holidays

    For USA holiday:

    1. To check a date holiday or not.

    from datetime import date
    import holidays
    
    # Select country
    us_holidays = holidays.US()
    
    # If it is a holidays then it returns True else False
    print('01-01-2018' in us_holidays)
    print('02-01-2018' in us_holidays)
    
    # What holidays is it?
    print(us_holidays.get('01-01-2018'))
    print(us_holidays.get('02-01-2018'))
    

    2. To list out all holidays in US:

    from datetime import date
    import holidays
    
    # Select country
    us_holidays = holidays.US()
    
    # Print all the holidays in US in year 2018
    for ptr in holidays.US(years = 2018).items():
        print(ptr)
    

    You can find holidays for any country you like the list of countries listed on my Blog. My Blog on Holidays

    Github Link of Holidays Python

提交回复
热议问题