holidays — Python Holiday Library
Overview
INLINECODE0 is a Python library that generates country- and subdivision-specific sets of government-designated holidays on the fly. It covers 249 countries (ISO 3166-1) and supports subdivisions (states, provinces, regions) via ISO 3166-2 codes.
The central object is HolidayBase, which behaves like a Python dict mapping date → holiday name. All examples below can be run directly in the shell:
CODEBLOCK0
Installation
IMPORTANT: Always use a virtual environment or --break-system-packages flag.
CODEBLOCK1
For production use, pin to a specific version:
CODEBLOCK2
Quick Reference
| Task | Method |
|---|
| All holidays for a country/year | INLINECODE5 |
| Holidays for a subdivision |
country_holidays('US', subdiv='CA', years=2024) |
| Holidays in a date range |
holidays_obj['2024-01-01':'2024-01-31'] |
| Check if a date is a holiday |
holidays_obj.get('2024-12-25') → name or
None |
| Add custom holidays |
holidays_obj.update({'2024-07-10': 'My Birthday!'}) |
| List all supported countries |
list_supported_countries() |
| List countries with localization |
list_localized_countries() |
Core API
country_holidays() — Main Function
CODEBLOCK3
Returns a HolidayBase object (dict-like: {date: name}).
Common Tasks
1. Get All Holidays for a Country in a Year
CODEBLOCK4
2. Get Holidays for a Subdivision (State / Province)
Use the ISO 3166-2 subdivision code (e.g. 'CA' for California, 'BY' for Bavaria).
CODEBLOCK5
3. Get Holidays Within a Date Range
Slice the HolidayBase object with date strings ('YYYY-MM-DD'):
CODEBLOCK6
4. Check if a Specific Date is a Holiday
INLINECODE20 returns the holiday name if the date is a holiday, or None if it is not.
CODEBLOCK7
Tip: Use if date in holidays_obj: for a boolean check (faster than .get()).
5. Working with Custom Holidays
SECURITY NOTE: Only use custom holidays if the user explicitly provides or requests them. Never assume a file location exists.
ALWAYS ask the user for the file path rather than using a default location. If they don't have a custom holidays file, skip this feature.
Example workflow:
- 1. Ask user: "Do you have a custom holidays JSON file you'd like to include?"
- If yes, ask: "What's the full path to your custom holidays file?"
- Only then load and merge:
CODEBLOCK8
Custom holidays file format:
CODEBLOCK9
6. List All Supported Countries and Subdivisions
CODEBLOCK10
7. Use Localized (Translated) Holiday Names
Language codes:
- - Use ISO 639-1 codes (e.g.,
en, de, fr) - Some countries use locale-specific codes (e.g.,
en_US, zh_CN) - If an unsupported language is requested, the library falls back to the default language
Step 1: Find countries with localization support
CODEBLOCK11
Step 2: Generate holidays in a specific language
CODEBLOCK12
Key Behaviours to Know
- -
observed=True (default): When a holiday falls on a weekend, the observed date (typically Monday) is included. Set observed=False to get only the statutory date. expand=True (default): If you check a date outside the years range, the library automatically adds that year. Set expand=False to prevent this.- Multiple years: Pass a list to
years to load several years at once: years=[2023, 2024, 2025]. - Date keys: The
HolidayBase dict accepts datetime.date, datetime.datetime, or 'YYYY-MM-DD' strings interchangeably as keys. - Country codes: Use ISO 3166-1 alpha-2 (e.g.
'US', 'GB', 'DE'). Aliases like 'UK' are supported when include_aliases=True.
Dependencies
- - Python: 3.10+
- Package:
holidays (PyPI). Install with: INLINECODE46 - No external system dependencies required
Security Considerations
- 1. Package installation: Use
--break-system-packages flag (required in this environment) and consider pinning to a specific version - Custom holidays files: Only load custom holidays when explicitly requested by the user with a user-provided path
- File access: Verify file existence before reading to avoid exposing directory structure
holidays — Python 假日库
概述
holidays 是一个 Python 库,可动态生成特定国家和地区的政府指定假日集合。它覆盖 249 个国家(ISO 3166-1),并通过 ISO 3166-2 代码支持地区(州、省、区域)。
核心对象是 HolidayBase,其行为类似于 Python 的 dict,映射 date → holiday name。以下所有示例均可直接在 shell 中运行:
bash
python <
你的代码
EOF
或者(如果通过 uv 安装包)
uv run - <
你的代码
EOF
安装
重要提示:始终使用虚拟环境或 --break-system-packages 标志。
bash
pip install holidays --break-system-packages
生产环境使用请锁定特定版本:
bash
pip install holidays==0.58 --break-system-packages
快速参考
| 任务 | 方法 |
|---|
| 获取某国/某年所有假日 | countryholidays(US, years=2024) |
| 获取某地区假日 |
countryholidays(US, subdiv=CA, years=2024) |
| 获取日期范围内的假日 | holidays_obj[2024-01-01:2024-01-31] |
| 检查某日期是否为假日 | holidays_obj.get(2024-12-25) → 名称或 None |
| 添加自定义假日 | holidays_obj.update({2024-07-10: 我的生日!}) |
| 列出所有支持的国家 | list
supportedcountries() |
| 列出支持本地化的国家 | list
localizedcountries() |
核心 API
country_holidays() — 主函数
python
country_holidays(
country, # ISO 3166-1 alpha-2 代码,例如 US、GB、DE
subdiv=None, # ISO 3166-2 地区代码,例如 CA、TX、BY
years=None, # 整数或整数列表,例如 2024 或 [2023, 2024]
expand=True, # 检查当前范围外的日期时自动扩展年份
observed=True, # 包含调休假日(例如周末假日→周一)
language=None, # 假日名称的 ISO 639-1 语言代码,例如 en、de
categories=None, # 过滤特定假日类别(因国家而异)
)
返回一个 HolidayBase 对象(类似字典:{date: name})。
常见任务
1. 获取某国某年的所有假日
python
from holidays import country_holidays
usholidays = countryholidays(US, years=2024)
for date, name in sorted(us_holidays.items()):
print(date, name)
2. 获取某地区(州/省)的假日
使用 ISO 3166-2 地区代码(例如 CA 代表加利福尼亚州,BY 代表巴伐利亚州)。
python
from holidays import country_holidays
caholidays = countryholidays(US, subdiv=CA, years=2024)
for date, name in sorted(ca_holidays.items()):
print(date, name)
3. 获取日期范围内的假日
使用日期字符串(YYYY-MM-DD)对 HolidayBase 对象进行切片:
python
from holidays import country_holidays
caholidays = countryholidays(US, subdiv=CA, years=2024)
for day in ca_holidays[2024-01-01:2024-01-31]:
print(f{day}: {ca_holidays.get(day)})
4. 检查特定日期是否为假日
.get() 如果日期是假日则返回假日名称,否则返回 None。
python
from holidays import country_holidays
caholidays = countryholidays(US, subdiv=CA)
12月25日是假日吗?
name = ca_holidays.get(2024-12-25)
print(name) # → Christmas Day
12月26日是假日吗?
name = ca_holidays.get(2024-12-26)
print(name) # → None
提示: 使用 if date in holidays_obj: 进行布尔检查(比 .get() 更快)。
5. 使用自定义假日
安全提示: 仅在用户明确提供或要求时使用自定义假日。切勿假定文件位置存在。
始终询问用户文件路径,而不是使用默认位置。如果他们没有自定义假日文件,请跳过此功能。
示例工作流程:
- 1. 询问用户:您是否有要包含的自定义假日 JSON 文件?
- 如果是,询问:自定义假日文件的完整路径是什么?
- 然后加载并合并:
python
import json
from pathlib import Path
from holidays import country_holidays
仅在用户明确提供路径时使用
custom_file = Path(/path/user/provided/custom-holidays.json)
读取前验证文件是否存在
if custom_file.exists():
with open(custom_file) as f:
custom_data = json.load(f)
holidays2024 = countryholidays(US, years=2024)
holidays2024.update(customdata)
print(holidays_2024.get(2024-07-10)) # → 我的生日!(如果已定义)
else:
print(f文件未找到:{custom_file})
自定义假日文件格式:
json
{
2024-07-10: 我的生日!,
2024-10-01: 家庭庆祝
}
6. 列出所有支持的国家和地区
python
from holidays import listsupportedcountries
include_aliases=True 也会返回常用别名(例如 UK 代表 GB)
supported = list
supportedcountries(include_aliases=True)
print(supported[US]) # → 支持的美国地区代码列表
7. 使用本地化(翻译)的假日名称
语言代码:
- - 使用 ISO 639-1 代码(例如 en、de、fr)
- 某些国家使用特定区域代码(例如 enUS、zhCN)
- 如果请求不支持的语言,库会回退到默认语言
步骤 1:查找支持本地化的国家
python
from holidays import listlocalizedcountries
获取所有支持多种语言的国家
localized = list
localizedcountries(include_aliases=True)
检查特定国家是否支持本地化
if MY in localized:
print(f马来西亚支持:{localized[MY]})
# 输出:马来西亚支持:[en
MY, msMY, zh_CN, ...]
步骤 2:生成特定语言的假日
python
from holidays import country_holidays
马来语的马来西亚假日
my
holidaysms = country
holidays(MY, years=2025, language=msMY)
for date, name in sorted(my
holidaysms.items())[:3]:
print(f{date}: {name})
英语的相同假日
my
holidaysen = country
holidays(MY, years=2025, language=enMY)
for date, name in sorted(my
holidaysen.items())[:3]:
print(f{date}: {name})
需要了解的关键行为
- - observed=True(默认): 当假日落在周末时,会包含调休日期(通常是周一)。设置 observed=False 仅获取法定日期。
- expand=True(默认): 如果你检查 years 范围之外的日期,库会自动添加该年份。设置 expand=False 可防止此行为。
- 多个年份: 向 years 传递列表可一次加载多个年份:years=[2023, 2024, 2025]。
- 日期键: HolidayBase 字典接受 datetime.date、datetime.datetime 或 YYYY-MM-DD 字符串作为键,可互换使用。
- 国家代码: 使用 ISO 3166-1 alpha-2(例如 US、GB、DE)。当 include_aliases=True 时支持 UK 等别名。
依赖项