本文目录导读:

在Python中判断系统节假日,我推荐几种实用方法:
使用 chinesecalendar 库(推荐)
这是最常用的中国节假日判断库:
# 安装:pip install chinesecalendar
from datetime import date
import chinesecalendar
def is_holiday(date_obj):
"""判断是否为节假日"""
from chinesecalendar import is_holiday
return is_holiday(date_obj)
# 使用示例
today = date.today()
print(f"{today} 是节假日吗?{is_holiday(today)}")
# 判断特定日期
test_date = date(2024, 2, 10) # 2024年春节
print(f"{test_date} 是节假日吗?{is_holiday(test_date)}")
使用 holidays 库(国际通用)
# 安装:pip install holidays
import holidays
# 中国节假日
cn_holidays = holidays.China() # 注意:此库可能不是特别准确
# 检查特定日期
def check_with_holidays(date_obj):
return date_obj in cn_holidays
# 使用示例
test_date = date(2024, 1, 1)
print(f"{test_date} 是节假日:{test_date in cn_holidays}")
使用 API 接口(最准确)
import requests
from datetime import date, datetime
def check_holiday_api(date_str=None):
"""
使用节假日API判断
推荐:http://timor.tech/api/holiday/
"""
if date_str is None:
date_str = date.today().strftime('%Y-%m-%d')
url = f"http://timor.tech/api/holiday/info/{date_str}"
try:
response = requests.get(url, timeout=5)
data = response.json()
if data.get('code') == 0:
holiday_info = data['type']
# type: 0=工作日, 1=周末, 2=节假日, 3=调休上班
return {
'is_holiday': holiday_info['type'] in [1, 2],
'detail': holiday_info['name'] if holiday_info['type'] == 2 else None,
'is_weekend': holiday_info['type'] == 1,
'is_workday': holiday_info['type'] == 0
}
except Exception as e:
print(f"API请求失败: {e}")
return None
# 使用示例
result = check_holiday_api()
if result:
print(f"今天是否节假日:{result['is_holiday']}")
自定义节假日数据(离线方案)
import json
from datetime import date
class ChinaHolidayChecker:
def __init__(self, holiday_data_file=None):
"""初始化,可以从文件加载,也可以硬编码"""
self.holidays = {
# 2024年节假日
'2024-01-01': '元旦', # 元旦
'2024-02-10': '春节', # 春节
'2024-02-11': '春节',
'2024-02-12': '春节',
'2024-04-04': '清明节', # 清明节
'2024-05-01': '劳动节', # 劳动节
'2024-06-10': '端午节', # 端午节
'2024-09-17': '中秋节', # 中秋节
'2024-10-01': '国庆节', # 国庆节
'2024-10-02': '国庆节',
'2024-10-03': '国庆节',
}
# 调休上班日
self.work_weekends = {
'2024-02-04': '春节调休',
'2024-02-18': '春节调休',
'2024-04-07': '清明调休',
'2024-04-28': '劳动节调休',
'2024-05-11': '劳动节调休',
'2024-09-14': '中秋调休',
'2024-09-29': '国庆调休',
'2024-10-12': '国庆调休',
}
if holiday_data_file:
self.load_from_file(holiday_data_file)
def is_holiday(self, date_obj):
"""判断是否为节假日"""
date_str = date_obj.strftime('%Y-%m-%d')
# 检查是否为调休上班日
if date_str in self.work_weekends:
return False
# 检查是否为节假日
if date_str in self.holidays:
return True
# 检查是否为周末
return date_obj.weekday() >= 5
def get_holiday_name(self, date_obj):
"""获取节假日名称"""
date_str = date_obj.strftime('%Y-%m-%d')
if date_str in self.holidays:
return self.holidays[date_str]
elif date_str in self.work_weekends:
return f"调休上班({self.work_weekends[date_str]})"
elif date_obj.weekday() == 5:
return "周六"
elif date_obj.weekday() == 6:
return "周日"
else:
return "工作日"
# 使用示例
checker = ChinaHolidayChecker()
today = date.today()
print(f"{today} 是节假日:{checker.is_holiday(today)}")
print(f"{today} 名称:{checker.get_holiday_name(today)}")
综合最佳实践
class SmartHolidayChecker:
"""智能节假日判断器,结合多种方案"""
def __init__(self):
self.decorator_checker = None
self.api_checker = None
self.local_checker = ChinaHolidayChecker()
# 尝试导入第三方库
try:
from chinesecalendar import is_holiday
self.decorator_checker = is_holiday
except ImportError:
pass
def is_holiday(self, date_obj):
"""综合判断是否节假日"""
# 1. 优先使用第三方库
if self.decorator_checker:
try:
return self.decorator_checker(date_obj)
except:
pass
# 2. 尝试API
if self.api_checker:
result = self.api_checker(date_obj.strftime('%Y-%m-%d'))
if result:
return result['is_holiday']
# 3. 使用本地数据
return self.local_checker.is_holiday(date_obj)
# 使用
checker = SmartHolidayChecker()
print(f"{checker.is_holiday(date.today())}")
推荐方案
- 首选:
chinesecalendar库(自动更新,维护良好) - 次选:API接口(实时准确,但需要网络)
- 备用:自定义数据库(离线可用)
建议在实际项目中使用第一种方案,或者将前两种方案结合使用。