因为工作业务需要,需要判断得到的日期是否是节假日(包括周末),并返回最近的工作日(如果获得的日期就是工作日,则返回该日期本身)
自己实现其实很麻烦,我是通过workalendar这个第三方组件包实现的。
首先下载安装:
pip install workalendar
2018-08-02 14_30_46-cmd (Admin).png
2018-08-02 14_34_20-GitHub - peopledoc_workalendar_ Worldwide holidays and workdays computational to.png
如果需要实现该功能非常简单:
from workalendar.usa import core
def getworkday(day):
cal = core.UnitedStates()
return cal.find_following_working_day(day)
判断是否是节假日的实现方式:
from workalendar.usa import core
cal = core.UnitedStates()
cal.is_holiday(day)
获得2018年美国所有节日:
from workalendar.usa import core
cal = core.UnitedStates()
print(cal.holidays(2018))
以下是结果:
[(datetime.date(2019, 1, 1), 'New year'),
(datetime.date(2019, 1, 21), 'Birthday of Martin Luther King, Jr.'),
(datetime.date(2019, 2, 18), "Washington's Birthday"),
(datetime.date(2019, 5, 27), 'Memorial Day'),
(datetime.date(2019, 7, 4), 'Independence Day'),
(datetime.date(2019, 9, 2), 'Labor Day'),
(datetime.date(2019, 10, 14), 'Columbus Day'),
(datetime.date(2019, 11, 11), 'Veterans Day'),
(datetime.date(2019, 11, 28), 'Thanksgiving Day'),
(datetime.date(2019, 12, 25), 'Christmas Day')]
获得香港2018年所有节日
from workalendar.asia import hong_kong
cal = hong_kong.HongKong()
print(cal.holidays(2018))
以下是结果:
[(datetime.date(2018, 1, 1), 'New year'),
(datetime.date(2018, 2, 16), "Chinese Lunar New Year's Day"),
(datetime.date(2018, 2, 17), 'Second day of Chinese Lunar New Year'),
(datetime.date(2018, 2, 18), 'Third day of Chinese Lunar New Year'),
(datetime.date(2018, 2, 19), 'Third day of Chinese Lunar New Year shift'),
(datetime.date(2018, 3, 30), 'Good Friday'),
(datetime.date(2018, 3, 31), 'Easter Saturday'),
(datetime.date(2018, 4, 2), 'Easter Monday'),
(datetime.date(2018, 4, 5), 'Ching Ming Festival'),
(datetime.date(2018, 5, 1), 'Labour Day'),
(datetime.date(2018, 5, 22), "Buddha's Birthday"),
(datetime.date(2018, 6, 18), 'Tuen Ng Festival'),
(datetime.date(2018, 7, 1), 'SAR Establishment Day'),
(datetime.date(2018, 7, 2), 'SAR Establishment Day shift'),
(datetime.date(2018, 9, 25), 'Day After Mid-Autumn Festival'),
(datetime.date(2018, 10, 1), 'National Day'),
(datetime.date(2018, 10, 17), 'Chung Yeung Festival'),
(datetime.date(2018, 12, 25), 'Christmas Day'),
(datetime.date(2018, 12, 26), 'Boxing Day')]