简体   繁体   中英

Adding a range of dates as one holiday rule, instead of just a single date, in Pandas.tseries AbstractHolidayCalendar?

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?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM