在python中生成和使用假日
holidays的Python项目详细描述
用于生成国家、省和州的快速、高效的python库 在飞行中的特定假日集合。它旨在确定 具体日期是尽可能快和灵活的假期。
示例用法
fromdatetimeimportdateimportholidaysus_holidays=holidays.UnitedStates()# or:# us_holidays = holidays.US()# or:# us_holidays = holidays.CountryHoliday('US')# or, for specific prov / states:# us_holidays = holidays.CountryHoliday('US', prov=None, state='CA')date(2015,1,1)inus_holidays# Truedate(2015,1,2)inus_holidays# False# The Holiday class will also recognize strings of any format# and int/float representing a Unix timestamp'2014-01-01'inus_holidays# True'1/1/2014'inus_holidays# True1388597445inus_holidays# Trueus_holidays.get('2014-01-01')# "New Year's Day"us_holidays['2014-01-01':'2014-01-03']# [date(2014, 1, 1)]us_pr_holidays=holidays.UnitedStates(state='PR')# or holidays.US(...), or holidays.CountryHoliday('US', state='PR')# some holidays are only present in parts of a country'2018-01-06'inus_holidays# False'2018-01-06'inus_pr_holidays# True# Easily create custom Holiday objects with your own dates instead# of using the pre-defined countries/states/provinces availablecustom_holidays=holidays.HolidayBase()# Append custom holiday dates by passing:# 1) a dict with date/name key/value pairs,custom_holidays.append({"2015-01-01":"New Year's Day"})# 2) a list of dates (in any format: date, datetime, string, integer),custom_holidays.append(['2015-07-01','07/04/2015'])# 3) a single date itemcustom_holidays.append(date(2015,12,25))date(2015,1,1)incustom_holidays# Truedate(2015,1,2)incustom_holidays# False'12/25/2015'incustom_holidays# True# For more complex logic like 4th Monday of January, you can inherit the# HolidayBase class and define your own _populate(year) method. See below# documentation for examples.
安装
最新的稳定版本始终可以通过pip安装或更新:
$ pip install holidays
如果上述操作失败,请改用Easy_安装:
$ easy_install holidays
可用国家/地区
Country | Abbr | Provinces/States Available |
---|---|---|
Argentina | AR | None |
Aruba | AW | None |
Australia | AU | prov = ACT (default), NSW, NT, QLD, SA, TAS, VIC, WA |
Austria | AT | prov = B, K, N, O, S, ST, T, V, W (default) |
Belarus | BY | None |
Belgium | BE | None |
Brazil | BR | state = AC, AL, AP, AM, BA, CE, DF, ES, GO, MA, MT, MS, MG, PA, PB, PE, PI, RJ, RN, RS, RO, RR, SC, SP, SE, TO |
Bulgaria | BG | None |
Canada | CA | prov = AB, BC, MB, NB, NL, NS, NT, NU, ON (default), PE, QC, SK, YU |
Colombia | CO | None |
Croatia | HR | None |
Czechia | CZ | None |
Denmark | DK | None |
England | None | |
Estonia | EE | None |
EuropeanCentralBank | ECB,TAR | Trans-European Automated Real-time Gross Settlement (TARGET2) |
Finland | FI | None |
France | FRA | Métropole (default), Alsace-Moselle, Guadeloupe, Guyane, Martinique, Mayotte, Nouvelle-Calédonie, La Réunion, Polynésie Française, Saint-Barthélémy, Saint-Martin, Wallis-et-Futuna |
Germany | DE | prov = BW, BY, BE, BB, HB, HH, HE, MV, NI, NW, RP, SL, SN, ST, SH, TH |
Hungary | HU | None |
Iceland | IS | None |
India | IND | prov = AS, SK, CG, KA, GJ, BR, RJ, OD, TN, AP, WB, KL, HR, MH, MP, UP, UK, TN |
Ireland | IE | None |
IsleOfMan | None | |
Italy | IT | prov = AN, AO, BA, BL, BO, BS, BZ, CB, Cesena, CH, CS, CT, EN, FC, FE, FI, Forlì, FR, GE, GO, IS, KR, LT, MB, MI, MO, MN, MS, NA, PA, PC, PD, PG, PR, RM, SP, TS, VI |
Japan | JP | None |
Kenya | KE | None |
Lithuania | LT | None |
Luxembourg | LU | None |
Mexico | MX | None |
Netherlands | NL | None |
NewZealand | NZ | prov = NTL, AUK, TKI, HKB, WGN, MBH, NSN, CAN, STC, WTL, OTA, STL, CIT |
Northern Ireland | None | |
Norway | NO | None |
Peru | PE | None |
Poland | PL | None |
Portugal | PT | None |
PortugalExt | PTE | Portugal plus extended days most people have off |
Russia | RU | None |
Scotland | None | |
Slovakia | SK | None |
Slovenia | SI | None |
South Africa | ZA | None |
Spain | ES | prov = AND, ARG, AST, CAN, CAM, CAL, CAT, CVA, EXT, GAL, IBA, ICA, MAD, MUR, NAV, PVA, RIO |
Sweden | SE | None |
Switzerland | CH | prov = AG, AR, AI, BL, BS, BE, FR, GE, GL, GR, JU, LU, NE, NW, OW, SG, SH, SZ, SO, TG, TI, UR, VD, VS, ZG, ZH |
Ukraine | UA | None |
UnitedKingdom | UK | None |
UnitedStates | US | state = AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MD, MH, MA, MI, FM, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VA, VI, WA, WV, WI, WY |
Wales | None |
API
- 班级假期。假期基数(年=[],展开=真,观察=真,验证=无,状态=无)
- 用于创建假日国家/地区类的基类。
参数:
- 年
- 指定假日对象所在年份的整数列表 应该预先生成。这通常只在设置expand 错了。(默认值:[])
- 展开
- 一个布尔值,指定是否在新的 年复一年的假期反对。(默认值:true)
- 观察到的
- 一个布尔值,当设置为true时,它将包括 在适当的时候,周末的假日。(默认值:true)
- prov
- 指定具有唯一法定假日的省份的字符串。 (默认值:澳大利亚='act',加拿大='on',新西兰=none)
- 状态
- 指定具有唯一法定假日的状态的字符串。 (默认值:unitedstates=none)
方法:
- 获取(键,默认值=无)
- 返回一个字符串,其中包含日期键中假日的名称 可以是日期、日期时间、字符串、Unicode、字节、整数或浮点类型。如果 多个假日在同一天,名字之间用 逗号
- 获取列表(键)
- 与get相同,只是返回假日名称的列表而不是逗号 分隔字符串
- 弹出(键,默认值=无)
- 与get相同,只是从假日对象中删除了键
- 更新/追加
- 接受{date:name}对字典、日期列表,甚至是单数 date/string/timestamp对象并将它们添加到假日列表中
更多示例
# Simplest example possible>>>fromdatetimeimportdate>>>importholidays>>>date(2014,1,1)inholidays.US()True>>date(2014,1,2)inholidays.US()False# But this is not efficient because it is initializing a new Holiday object# and generating a list of all the holidays in 2014 during each comparison# It is more efficient to create the object only once>>>us_holidays=holidays.US()>>>date(2014,1,1)inus_holidaysTrue>>date(2014,1,2)inus_holidaysFalse# Each country has two class names that can be called--a full name# and an abbreviation. Use whichever you prefer.>>>holidays.UnitedStates()==holidays.US()True>>>holidays.Canada()==holidays.CA()True>>>holidays.US()==holidays.CA()False# Let's print out the holidays in 2014 specific to California, USA>>>fordate,nameinsorted(holidays.US(state='CA',years=2014).items()):>>>print(date,name)2014-01-01NewYear's Day2014-01-20MartinLutherKing,Jr.Day2014-02-15SusanB.AnthonyDay2014-02-17Washington's Birthday2014-03-31CésarChávezDay2014-05-26MemorialDay2014-07-04IndependenceDay2014-09-01LaborDay2014-10-13ColumbusDay2014-11-11VeteransDay2014-11-27Thanksgiving2014-12-25ChristmasDay# So far we've only checked holidays in 2014 so that's the only year the# Holidays object has generated>>>us_holidays.yearsset([2014])>>>len(us_holidays)10# Because by default the `expand` param is True the Holiday object will add# holidays from other years as they are required.>>>date(2013,1,1)inus_holidaysTrue>>>us_holidays.yearsset([2013,2014])>>>len(us_holidays)20# If we change the `expand` param to False the Holiday object will no longer# add holidays from new years>>>us_holidays.expand=False>>>date(2012,1,1)inus_holidaysFalse>>>us.holidays.expand=True>>>date(2012,1,1)inus_holidaysTrue# January 1st, 2012 fell on a Sunday so the statutory holiday was observed# on the 2nd. By default the `observed` param is True so the holiday list# will include January 2nd, 2012 as a holiday.>>>date(2012,1,1)inus_holidaysTrue>>>us_holidays[date(2012,1,1)]"New Year's Eve">>>date(2012,1,2)inus_holidaysTrue>>>us_holidays.get(date(2012,1,2))"New Year's Eve (Observed)"# The `observed` and `expand` values can both be changed on the fly and the# holiday list will be adjusted accordingly>>>us_holidays.observed=False>>>date(2012,1,2)inus_holidaysFalseus_holidays.observed=True>>date(2012,1,2)inus_holidaysTrue# Holiday objects can be added together and the resulting object will# generate the holidays from all of the initial objects>>>north_america=holidays.CA()+holidays.US()+holidays.MX()>>>north_america.get('2014-07-01')"Canada Day">>>north_america.get('2014-07-04')"Independence Day"# The other form of addition is also available>>>north_america=holidays.Canada()>>>north_america+=holidays.UnitedStates()>>>north_america+=holidays.Mexico()>>>north_america.country['CA','US','MX']# We can even get a set of holidays that include all the province- or# state-specific holidays using the built-in sum() function>>>a=sum([holidays.CA(prov=x)forxinholidays.CA.PROVINCES])>>>a.provPROVINCES=['AB','BC','MB','NB','NL','NS','NT','NU','ON','PE','QC','SK','YU']# Sometimes we may not be able to use the official federal statutory# holiday list in our code. Let's pretend we work for a company that# does not include Columbus Day as a statutory holiday but does include# "Ninja Turtle Day" on July 13th. We can create a new class that inherits# the UnitedStates class and the only method we need to override is _populate()>>>fromdateutil.relativedeltaimportrelativedelta>>>classCorporateHolidays(holidays.UnitedStates):>>>def_populate(self,year):>>># Populate the holiday list with the default US holidays>>>holidays.UnitedStates._populate(self,year)>>># Remove Columbus Day>>>self.pop(date(year,10,1)+relativedelta(weekday=MO(+2)),None)>>># Add Ninja Turtle Day>>>self[date(year,7,13)]="Ninja Turtle Day">>>date(2014,10,14)inHolidays(country="US")True>>>date(2014,10,14)inCorporateHolidays(country="US")False>>>date(2014,7,13)inHolidays(country="US")False>>>date(2014,7,13)inCorporateHolidays(country="US")True# We can also inherit from the HolidayBase class which has an empty# _populate method so we start with no holidays and must define them# all ourselves. This is how we would create a holidays class for a country# that is not supported yet.>>>classNewCountryHolidays(holidays.HolidayBase):>>>def_populate(self,year):>>>self[date(year,1,2)]="Some Federal Holiday">>>self[date(year,2,3)]="Another Federal Holiday">>>hdays=NewCountryHolidays()# We can also include prov/state specific holidays in our new class.>>>classNewCountryHolidays(holidays.HolidayBase):>>>def_populate(self,year):>>># Set default prov if not provided>>>ifself.prov==None:>>>self.prov='XX'>>>self[date(year,1,2)]="Some Federal Holiday">>>ifself.prov=='XX':>>>self[date(year,2,3)]="Special XX province-only holiday">>>ifself.prov=='YY':>>>self[date(year,3,4)]="Special YY province-only holiday">>>hdays=NewCountryHolidays()>>>hdays=NewCountryHolidays(prov='XX')# If you write the code necessary to create a holiday class for a country# not currently supported please contribute your code to the project!# Perhaps you just have a list of dates that are holidays and want to turn# them into a Holiday class to access all the useful functionality. You can# use the append() method which accepts a dictionary of {date: name} pairs,# a list of dates, or even singular date/string/timestamp objects.>>>custom_holidays=holidays.HolidaysBase()>>>custom_holidays.append(['2015-01-01','07/04/2015'])>>>custom_holidays.append(date(2015,12,25))
>>> from datetime import date >>> holidays.US()[date(2013, 12, 31): date(2014, 1, 2)]
开发版本
最新的开发(beta)版本可以直接从github安装:
$ pip install --upgrade https://github.com/dr-prodigy/python-holidays/tarball/beta
所有的新功能总是先推送到beta分支,然后在 官方版本升级后的主分支。
运行测试
$ pip install flake8 $ flake8 holidays.py tests.py $ python tests.py
覆盖范围
$ pip install coverage
$ coverage run --omit=*site-packages* tests.py
$ coverage report -m
贡献
Issues和Pull Requests总是受欢迎的。
当使用修复和新功能时,请开始分叉/分支 从beta branch,工作在最新的代码和减少合并问题。
此外,只要可能,请为您的新代码提供100%的测试覆盖率。
非常感谢你的支持。
许可证
代码和文档根据麻省理工学院的许可证提供 (见LICENSE)。