API Reference
holidays.utils
country_holidays(country, subdiv=None, years=None, expand=True, observed=True, prov=None, state=None, language=None, categories=None)
Return a new dictionary-like HolidayBase object.
Include public holidays for the country matching country and other keyword arguments.
| Parameters: |
|
|---|
| Returns: |
|
|---|
The key of the dict-like HolidayBase object is the
date of the holiday, and the value is the name of the holiday itself.
Dates where a key is not present are not public holidays (or, if
observed is False, days when a public holiday is observed).
When passing the date as a key, the date can be expressed in one of the
following types:
datetime.date,datetime.datetime,- a
strof any format recognized bydateutil.parser.parse(), - or a
floatorintrepresenting a POSIX timestamp.
The key is always returned as a datetime.date object.
To maximize speed, the list of public holidays is built on the fly as
needed, one calendar year at a time. When the object is instantiated
without a years parameter, it is empty, but, unless expand is set
to False, as soon as a key is accessed the class will calculate that entire
year's list of holidays and set the keys with them.
If you need to list the holidays as opposed to querying individual dates,
instantiate the class with the years parameter.
Example usage:
>>> from holidays import country_holidays
>>> us_holidays = country_holidays('US')
# For a specific subdivision (e.g. state or province):
>>> calif_holidays = country_holidays('US', subdiv='CA')
The below will cause 2015 holidays to be calculated on the fly:
>>> from datetime import date
>>> assert date(2015, 1, 1) in us_holidays
This will be faster because 2015 holidays are already calculated:
>>> assert date(2015, 1, 2) not in us_holidays
The HolidayBase class also recognizes strings of many formats
and numbers representing a POSIX timestamp:
>>> assert '2014-01-01' in us_holidays
>>> assert '1/1/2014' in us_holidays
>>> assert 1388597445 in us_holidays
Show the holiday's name:
>>> us_holidays.get('2014-01-01')
"New Year's Day"
Check a range:
>>> us_holidays['2014-01-01': '2014-01-03']
[datetime.date(2014, 1, 1)]
List all 2020 holidays:
>>> us_holidays = country_holidays('US', years=2020)
>>> for day in sorted(us_holidays.items()):
... print(day)
(datetime.date(2020, 1, 1), "New Year's Day")
(datetime.date(2020, 1, 20), 'Martin Luther King Jr. Day')
(datetime.date(2020, 2, 17), "Washington's Birthday")
(datetime.date(2020, 5, 25), 'Memorial Day')
(datetime.date(2020, 7, 3), 'Independence Day (observed)')
(datetime.date(2020, 7, 4), 'Independence Day')
(datetime.date(2020, 9, 7), 'Labor Day')
(datetime.date(2020, 10, 12), 'Columbus Day')
(datetime.date(2020, 11, 11), 'Veterans Day')
(datetime.date(2020, 11, 26), 'Thanksgiving Day')
(datetime.date(2020, 12, 25), 'Christmas Day')
Some holidays are only present in parts of a country:
>>> us_pr_holidays = country_holidays('US', subdiv='PR')
>>> assert '2018-01-06' not in us_holidays
>>> assert '2018-01-06' in us_pr_holidays
Append custom holiday dates by passing one of:
- a
dictwith date/name key/value pairs (e.g.{'2010-07-10': 'My birthday!'}), - a list of dates (as a
datetime.date,datetime.datetime,str,int, orfloat); "Holiday" will be used as a description, - or a single date item (of one of the types above); "Holiday" will be used as a description:
>>> custom_holidays = country_holidays('US', years=2015)
>>> custom_holidays.update({'2015-01-01': "New Year's Day"})
>>> custom_holidays.update(['2015-07-01', '07/04/2015'])
>>> custom_holidays.update(date(2015, 12, 25))
>>> assert date(2015, 1, 1) in custom_holidays
>>> assert date(2015, 1, 2) not in custom_holidays
>>> assert '12/25/2015' in custom_holidays
For more complex logic, like 4th Monday of January, you can inherit the
HolidayBase class and define your own _populate method.
See documentation for examples.
financial_holidays(market, subdiv=None, years=None, expand=True, observed=True, language=None, categories=None)
Return a new dictionary-like HolidayBase object.
Include public holidays for the financial market matching market and other keyword
arguments.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Example usage:
>>> from holidays import financial_holidays
>>> nyse_holidays = financial_holidays('XNYS')
See country_holidays() documentation for further details and examples.
list_localized_countries(include_aliases=True)
cached
Get all localized countries and languages they support.
| Parameters: |
|
|---|
| Returns: |
|
|---|
list_localized_financial(include_aliases=True)
cached
Get all localized financial markets and languages they support.
| Parameters: |
|
|---|
| Returns: |
|
|---|
list_supported_countries(include_aliases=True)
cached
Get all supported countries and their subdivisions.
| Parameters: |
|
|---|
| Returns: |
|
|---|
list_supported_financial(include_aliases=True)
cached
Get all supported financial markets and their subdivisions.
| Parameters: |
|
|---|
| Returns: |
|
|---|
list_long_breaks(instance, *, minimum_break_length=3, require_weekend_overlap=True)
Get consecutive holidays.
| Parameters: |
|
|---|
| Returns: |
|
|---|
holidays.holiday_base
CategoryArg = str | Iterable[str]
module-attribute
DateArg = date | tuple[int, int] | tuple[int, int, int]
module-attribute
DateLike = date | datetime | str | float | int
module-attribute
NameLookup = Literal['contains', 'exact', 'startswith', 'icontains', 'iexact', 'istartswith']
module-attribute
SpecialHoliday = tuple[int, int, str] | tuple[tuple[int, int, str], ...]
module-attribute
SubstitutedHoliday = tuple[int, int, int, int] | tuple[int, int, int, int, int] | tuple[tuple[int, int, int, int] | tuple[int, int, int, int, int], ...]
module-attribute
YearArg = int | Iterable[int]
module-attribute
HolidayBase(years=None, expand=True, observed=True, subdiv=None, prov=None, state=None, language=None, categories=None)
Bases: dict[date, str]
Represent a dictionary-like collection of holidays for a specific country or region.
This class inherits from dict and maps holiday dates to their names. It supports
customization by country and, optionally, by province or state (subdivision). A date
not present as a key is not considered a holiday (or, if observed is False, not
considered an observed holiday).
Keys are holiday dates, and values are corresponding holiday names. When accessing or assigning holidays by date, the following input formats are accepted:
datetime.datedatetime.datetimefloatorint(Unix timestamp)strof any format recognized bydateutil.parser.parse()
Keys are always returned as datetime.date objects.
To maximize performance, the holiday list is lazily populated one year at a time.
On instantiation, the object is empty. Once a date is accessed, the full calendar
year for that date is generated, unless expand is set to False. To pre-populate
holidays, instantiate the class with the years argument:
us_holidays = holidays.US(years=2020)
It is recommended to use the country_holidays() function for instantiation.
Example usage:
>>> from holidays import country_holidays
>>> us_holidays = country_holidays('US')
# For a specific subdivisions (e.g. state or province):
>>> california_holidays = country_holidays('US', subdiv='CA')
The below will cause 2015 holidays to be calculated on the fly:
>>> from datetime import date
>>> assert date(2015, 1, 1) in us_holidays
This will be faster because 2015 holidays are already calculated:
>>> assert date(2015, 1, 2) not in us_holidays
The HolidayBase class also recognizes strings of many formats
and numbers representing a POSIX timestamp:
>>> assert '2014-01-01' in us_holidays
>>> assert '1/1/2014' in us_holidays
>>> assert 1388597445 in us_holidays
Show the holiday's name:
>>> us_holidays.get('2014-01-01')
"New Year's Day"
Check a range:
>>> us_holidays['2014-01-01': '2014-01-03']
[datetime.date(2014, 1, 1)]
List all 2020 holidays:
>>> us_holidays = country_holidays('US', years=2020)
>>> for day in sorted(us_holidays.items()):
... print(day)
(datetime.date(2020, 1, 1), "New Year's Day")
(datetime.date(2020, 1, 20), 'Martin Luther King Jr. Day')
(datetime.date(2020, 2, 17), "Washington's Birthday")
(datetime.date(2020, 5, 25), 'Memorial Day')
(datetime.date(2020, 7, 3), 'Independence Day (observed)')
(datetime.date(2020, 7, 4), 'Independence Day')
(datetime.date(2020, 9, 7), 'Labor Day')
(datetime.date(2020, 10, 12), 'Columbus Day')
(datetime.date(2020, 11, 11), 'Veterans Day')
(datetime.date(2020, 11, 26), 'Thanksgiving Day')
(datetime.date(2020, 12, 25), 'Christmas Day')
Some holidays are only present in parts of a country:
>>> us_pr_holidays = country_holidays('US', subdiv='PR')
>>> assert '2018-01-06' not in us_holidays
>>> assert '2018-01-06' in us_pr_holidays
Append custom holiday dates by passing one of the following:
- A dict mapping date values to holiday names (e.g.
{'2010-07-10': 'My birthday!'}). - A list of date values (
datetime.date,datetime.datetime,str,int, orfloat); each will be added with 'Holiday' as the default name. - A single date value of any of the supported types above; 'Holiday' will be used as the default name.
>>> custom_holidays = country_holidays('US', years=2015)
>>> custom_holidays.update({'2015-01-01': "New Year's Day"})
>>> custom_holidays.update(['2015-07-01', '07/04/2015'])
>>> custom_holidays.update(date(2015, 12, 25))
>>> assert date(2015, 1, 1) in custom_holidays
>>> assert date(2015, 1, 2) not in custom_holidays
>>> assert '12/25/2015' in custom_holidays
For special (one-off) country-wide holidays handling use
special_public_holidays:
special_public_holidays = {
1977: ((JUN, 7, "Silver Jubilee of Elizabeth II"),),
1981: ((JUL, 29, "Wedding of Charles and Diana"),),
1999: ((DEC, 31, "Millennium Celebrations"),),
2002: ((JUN, 3, "Golden Jubilee of Elizabeth II"),),
2011: ((APR, 29, "Wedding of William and Catherine"),),
2012: ((JUN, 5, "Diamond Jubilee of Elizabeth II"),),
2022: (
(JUN, 3, "Platinum Jubilee of Elizabeth II"),
(SEP, 19, "State Funeral of Queen Elizabeth II"),
),
}
def _populate(self, year):
super()._populate(year)
...
For more complex logic, like 4th Monday of January, you can inherit the
HolidayBase class and define your own _populate()
method.
See documentation for examples.
| Parameters: |
|
|---|
| Returns: |
|
|---|
country
instance-attribute
The country's ISO 3166-1 alpha-2 code.
market
instance-attribute
The market's ISO 3166-1 alpha-2 code.
subdivisions = ()
class-attribute
instance-attribute
The subdivisions supported for this country (see documentation).
subdivisions_aliases = {}
class-attribute
instance-attribute
Aliases for the ISO 3166-2 subdivision codes with the key as alias and the value the ISO 3166-2 subdivision code.
special_holidays = {}
class-attribute
instance-attribute
A list of the country-wide special (as opposite to regular) holidays for a specific year.
weekend = {SAT, SUN}
class-attribute
instance-attribute
Country weekend days.
default_category = PUBLIC
class-attribute
instance-attribute
The entity category used by default.
default_language = None
class-attribute
instance-attribute
The entity language used by default.
supported_categories = (PUBLIC,)
class-attribute
instance-attribute
All holiday categories supported by this entity.
supported_languages = ()
class-attribute
instance-attribute
All languages supported by this entity.
start_year = DEFAULT_START_YEAR
class-attribute
instance-attribute
Start year of holidays presence for this entity.
end_year = DEFAULT_END_YEAR
class-attribute
instance-attribute
End year of holidays presence for this entity.
parent_entity = None
class-attribute
instance-attribute
Optional parent entity to reference as a base.
categories = categories
class-attribute
instance-attribute
Requested holiday categories.
expand = expand
instance-attribute
Whether the entire year is calculated when one date from that year is requested.
has_special_holidays = getattr(self, 'has_special_holidays', False)
instance-attribute
has_substituted_holidays = has_substituted_holidays
instance-attribute
language = language
instance-attribute
observed = observed
instance-attribute
Whether dates when public holiday are observed are included.
subdiv = subdiv
class-attribute
instance-attribute
The subdiv requested as ISO 3166-2 code or one of the aliases.
weekend_workdays = getattr(self, 'weekend_workdays', set())
instance-attribute
Working days moved to weekends.
years = _normalize_arguments(int, years)
instance-attribute
The years calculated.
get_subdivision_aliases()
classmethod
Get subdivision aliases.
| Returns: |
|
|---|
append(*args)
copy()
Return a copy of the object.
get(key, default=None)
Retrieve the holiday name(s) for a given date.
If the date is a holiday, returns the holiday name as a string.
If multiple holidays fall on the same date, their names are joined by a semicolon (;).
If the date is not a holiday, returns the provided default value (defaults to None).
| Parameters: |
|
|---|
| Returns: |
|
|---|
get_list(key)
Retrieve all holiday names for a given date.
| Parameters: |
|
|---|
| Returns: |
|
|---|
get_named(holiday_name, lookup='icontains', split_multiple_names=True)
Find all holiday dates matching a given name.
The search by default is case-insensitive and includes partial matches.
| Parameters: |
|
|---|
| Returns: |
|
|---|
get_closest_holiday(target_date=None, direction='forward')
Find the closest holiday relative to a given date.
If direction is "forward", returns the next holiday after target_date.
If direction is "backward", returns the previous holiday before target_date.
If target_date is not provided, the current date is used.
| Parameters: |
|
|---|
| Returns: |
|
|---|
get_nth_working_day(key, n)
Find the n-th working day from a given date.
Moves forward if n is positive, or backward if n is negative. If n is 0, returns the given date if it is a working day; otherwise the next working day.
| Parameters: |
|
|---|
| Returns: |
|
|---|
get_working_days_count(start, end)
Calculate the number of working days between two dates.
The date range works in a closed interval fashion [start, end] so both endpoints are included.
| Parameters: |
|---|
| Returns: |
|
|---|
is_weekend(key)
Check if the given date's week day is a weekend day.
| Parameters: |
|
|---|
| Returns: |
|
|---|
is_working_day(key)
Check if the given date is considered a working day.
| Parameters: |
|
|---|
| Returns: |
|
|---|
pop(key, default=None)
Remove a holiday for a given date and return its name.
If the specified date is a holiday, it will be removed, and its name will
be returned. If the date is not a holiday, the provided default value
will be returned instead.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
pop_named(holiday_name, lookup='icontains')
Remove all holidays matching the given name.
This method removes all dates associated with a holiday name, so they are no longer considered holidays. The search by default is case-insensitive and includes partial matches.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
update(*args)
Update the object, overwriting existing dates.
| Parameters: |
|
|---|
HolidaySum(h1, h2)
Bases: HolidayBase
Combine multiple holiday collections into a single dictionary-like object.
This class represents the sum of two or more HolidayBase instances.
The resulting object behaves like a dictionary mapping dates to holiday
names, with the following behaviors:
- The
holidaysattribute stores the original holiday collections as a list. - The
countryandsubdivattributes are combined from all operands and may become lists. - If multiple holidays fall on the same date, their names are merged.
- Holidays are generated (expanded) for all years included in the operands.
| Parameters: |
|
|---|
Example:
>>> from holidays import country_holidays
>>> nafta_holidays = country_holidays('US', years=2020) + country_holidays('CA') + country_holidays('MX')
>>> dates = sorted(nafta_holidays.items(), key=lambda x: x[0])
>>> from pprint import pprint
>>> pprint(dates[:10], width=72)
[(datetime.date(2020, 1, 1), "Año Nuevo; New Year's Day"),
(datetime.date(2020, 1, 20), 'Martin Luther King Jr. Day'),
(datetime.date(2020, 2, 3), 'Día de la Constitución'),
(datetime.date(2020, 2, 17), "Washington's Birthday"),
(datetime.date(2020, 3, 16), 'Natalicio de Benito Juárez'),
(datetime.date(2020, 4, 10), 'Good Friday'),
(datetime.date(2020, 5, 1), 'Día del Trabajo'),
(datetime.date(2020, 5, 25), 'Memorial Day'),
(datetime.date(2020, 7, 1), 'Canada Day'),
(datetime.date(2020, 7, 3), 'Independence Day (observed)')]
country
instance-attribute
Countries included in the addition.
market
instance-attribute
Markets included in the addition.
subdiv
instance-attribute
Subdivisions included in the addition.
years
instance-attribute
The years calculated.
holidays = []
instance-attribute
The original HolidayBase objects included in the addition.
supported_languages = (h1_language,) if h1_language else ()
instance-attribute
holidays.ical
CONTENT_LINE_MAX_LENGTH = 75
module-attribute
CONTENT_LINE_DELIMITER = '\r\n'
module-attribute
CONTENT_LINE_DELIMITER_WRAP = f'{CONTENT_LINE_DELIMITER} '
module-attribute
ICalExporter(instance, show_language=False)
Initialize iCalendar exporter.
| Parameters: |
|
|---|
holidays = instance
instance-attribute
show_language = show_language
instance-attribute
ical_timestamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
instance-attribute
holidays_version = __version__
instance-attribute
language = self._validate_language(language) if isinstance(language, str) and language in getattr(self.holidays, 'supported_languages', []) else None
instance-attribute
generate(return_bytes=False)
Generate iCalendar data.
| Parameters: |
|
|---|
| Returns: |
|
|---|
save_ics(file_path)
Export the calendar data to a .ics file.
While RFC 5545 does not specifically forbid filenames for .ics files, but it's advisable to follow general filesystem conventions and avoid using problematic characters.
| Parameters: |
|
|---|