Reputation: 183
I'm working on a Python script to offset a given start date with X number of business days according to a custom holiday calendar. Pandas.tseries seems to be a good choice.
When building my generic holiday calendar, I have come across examples on adding a single date to the holiday rules.
Example:
import pandas as pd
from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, Easter
from pandas.tseries.offsets import Day
class myCalendar(AbstractHolidayCalendar):
rules = [
Holiday('Off-day during Easter', month=1, day=1, offset=[Easter(), Day(-2)]),
Holiday('Christmas Day', month=12, day=25)
]
When using a function like this:
def offset_date(start, offset):
return start + pd.offsets.CustomBusinessDay(n=offset, calendar=myCalendar())
The dates within the rules will be skipped as expected.
But I now want to add 3 full weeks, 21 days to the rule set, with a given start-offset, instead of writing 21 rule lines to achieve the same thing?
I wonder if you guys know if it's possible to create a one-liner that adds 21 days to the rule set?
Upvotes: 1
Views: 488
Reputation: 13458
Here is one way to do it with a list comprehension, which keeps it short and readable:
class myCalendar(AbstractHolidayCalendar):
rules = [
Holiday("Off-day during Easter", month=1, day=1, offset=[Easter(), Day(-2)]),
Holiday("Christmas Day", month=12, day=25),
Holiday("Christmas Day", month=12, day=25),
] + [Holiday("Ski days", month=2, day=x) for x in range(1, 22)]
Here, a 21 days-off period starting February, 1st is added to the set of rules.
So that:
print(offset_date(pd.to_datetime("2023-01-31"), 1))
# 2023-02-22 00:00:00 as expected
Upvotes: 1