1.方法1:抓取网址json 

dic = {}

def getholiday(data_str):
    global dic
    if len(str(data_str)) != 10:
        print("日期格式不正确")
        return False
    import requests
    import json
    year = data_str[:4]
    data = data_str[5:]
    # print(year, data)
    if not dic:
        url = 'https://timor.tech/api/holiday/year/%s/' % year
        session = requests.session()
        headers={"User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Mobile Safari/537.36"}

        r = requests.get(url,headers=headers)
        # 保存页面
        json_text = r.content.decode()
        dic = json.loads(json_text)
    holiday = dic.get('holiday')
    print(holiday)
    get_dic = holiday.get(data)
    if get_dic:
        print("满足节假日")
        return True
    else:
        # print("不满足")
        return False

2.方法2:上面方法已经失效,读取本地文件

 


def getholiday(file=r"D:\新需求\holiday.json", data_str=''):
    import requests
    import json
    if not data_str:
        from datetime import datetime

        data_str = str(datetime.now().date())

    if len(str(data_str)) != 10:
        print("日期格式不正确")
        return False

    year = data_str[:4]
    data = data_str[5:]
    # print(year, data)

    try:
        with open(file, "r", encoding="utf-8") as json_file:
            dic = json.load(json_file)

        holiday = dic.get('holiday')
        # print(holiday)
        get_dic = holiday.get(data)
        if get_dic:
            print(data, "满足节假日")
            return True
        else:
            print(data, "不满足")
            return False
    except Exception as e:
            print(e)
            

3.方法3,使用chinese_calendar 库

https://files.pythonhosted.org/packages/fa/03/493c40e5e21f5318940f22c270152956afc3e9451b651682e4305041be96/chinese_calendar-1.8.1.tar.gz
pip install chinese_calendar
def getholiday(date_str=None):
    import datetime
    from chinese_calendar import get_holidays

    if date_str is None:
        now = datetime.datetime.now()
        target_date = now.date()
    else:
        target_date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()

    today = str(target_date)

    date_list = get_holidays(datetime.date(target_date.year, 1, 1), datetime.date(target_date.year, 12, 31))
    date_strings = [str(date) for date in date_list]

    if today in date_strings:
        print(today, "节假日")
        return True
    else:
        print(today, "非节假日")
        return False

# 使用今天日期
getholiday()

# 使用指定日期字符串,例如:"2023-02-03"
getholiday("2023-02-03")

4.扩展

让AI统计全年节假日和周末,调休