I want to create a class of holidays of Christmas and the day after, but I encounter a problem. There is one out of three special cases I cannot quite solve it.
Case1: Christmas is Friday, then the Holidays are Friday(12-25) and Saturday(12-26)(solved). This case happens in 2020
Case2: Christmas is Saturday, then the Holidays are Saturday(12-25) and Monday(12-27)(solved). This case happens in 2021
Case3: Christmas is Sunday, then the Holidays are Monday(12-26) and Tuesday(12-27)(unsolved). This case happens in 2016
Case 3 could be solved if observance= monday_to_tuesday
was available, but sadly it isn't, which is why I am here asking for help, since the pandas tseries user guide doesn't say anything about creating a custom observance or anything about the situation where the observance is from any weekday.
The class I am working on is the following:
from pandas.tseries.holiday import Holiday, sunday_to_monday, AbstractHolidayCalendar
import pandas as pd
import datetime as dt
class MyHolidays(AbstractHolidayCalendar):
rules = [Holiday('Christmas',month=12,day=25, observance= sunday_to_monday),
Holiday('Boxingday',month=12,day=26, observance= sunday_to_monday)]
cal= MyHolidays()
if __name__ == '__main__':
myholidays =cal.holidays(start = dt.datetime(2016,1,1), end=dt.datetime(2021,12,31))
temp_s = pd.Series(myholidays)
print(temp_s)
Is there anyway to solve my problem? Thank you in advance
You can roll your own observance function following the existing ones . They are just regular python functions, so you can also use a lambda as shown here:
from pandas.tseries.holiday import Holiday, sunday_to_monday, AbstractHolidayCalendar
import pandas as pd
import datetime as dt
class MyHolidays(AbstractHolidayCalendar):
rules = [Holiday('Christmas',month=12,day=25, observance= sunday_to_monday),
Holiday('Boxingday',month=12,day=26, observance= lambda d: d + dt.timedelta(1) if d.weekday() == 0 or d.weekday() == 6 else d )]
cal= MyHolidays()
if __name__ == '__main__':
myholidays =cal.holidays(start = dt.datetime(2016,1,1), end=dt.datetime(2021,12,31))
temp_s = pd.Series(myholidays)
print(temp_s)
Output:
0 2016-12-26
1 2016-12-27
2 2017-12-25
3 2017-12-26
4 2018-12-25
5 2018-12-26
6 2019-12-25
7 2019-12-26
8 2020-12-25
9 2020-12-26
10 2021-12-25
11 2021-12-27
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.