[英]which holidays been celebrated in particular date and in which countries
我想知道特定日期(在此示例中為今天的日期)是否是世界上某個地方的假期。 如果是 - 我想在每個元組中創建帶有元組的列表 - (假期名稱,世界上的哪個地方)。 如果它不是任何地方的假期 - 空列表。 我試圖導入假期,但我需要像這個例子一樣在每個國家運行:有人有更高效的東西嗎?
from datetime import date
import holidays
listOfHolidays = []
for ptr in holidays.ISR(years=date.today().year).items():
if date.today() == ptr[0]:
listOfHolidays.append(tuple((ptr[1], "ISRAEL")))
for ptr in holidays.US(years=date.today().year).items():
if date.today() == ptr[0]:
listOfHolidays.append((tuple(ptr[1], "US")))
for ptr in holidays.UK(years=date.today().year).items():
if date.today() == ptr[0]:
listOfHolidays.append((tuple(ptr[1], "UK")))
for ptr in holidays.CHN(years=date.today().year).items():
if date.today() == ptr[0]:
listOfHolidays.append((tuple(ptr[1], "CHN")))
print(listOfHolidays)
由於holidays
package 的結構,您確實必須遍歷所有受支持的區域。 function holidays.list_supported_countries
可以幫助您。 好消息是您可以在國家 object 中進行直接查找,而無需手動搜索 dict 項:
list_of_holidays = []
target = date.today()
for country in holidays.list_supported_countries():
country = getattr(holidays, country)()
holiday = country.get(target)
if holiday is not None:
list_of_holidays.append((holiday, country.country))
您可以在支持海象運算符的 python 版本中將其寫為理解:
list_of_holidays = [(c[target], c.country) for country in holidays.list_supported_countries()
if target in (c := getattr(holidays, country)())]
問題是這里會有很多重復,因為幾乎每個支持的國家都有多種引用方式。 這也是一個問題,因為您不想在運行中一遍又一遍地生成相同的列表。
在檢查圖書館時,我發現檢查國家 class 是否“真實”的最可靠方法是通過_populate
方法檢查它是否引入了任何新假期。 您可以為此添加條件:
list_of_holidays = []
target = date.today()
for country in holidays.list_supported_countries():
country_obj = getattr(holidays, country)
country = country_obj()
holiday = country.get(target)
if holiday is not None and '_populate' in country_obj.__dict__:
list_of_holidays.append((holiday, country.country))
或者作為一種理解:
list_of_holidays = [(c[target], c.country) for country in holidays.list_supported_countries()
if target in (c := getattr(holidays, country)()) and '_populate' in c.__class__.__dict__]
最后,當您使用country
屬性時,國家代碼總是作為名稱給出。 如果您想要更清晰的內容,我發現最好使用實現_populate
方法的 class 的名稱。 對於第二個循環,將(holiday, country.country)
替換為
(holiday, country_obj.__name__)
對於第二個列表理解,將(c[target], c.country)
替換為
(c[target], c.__class__.__name__)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.