Pandas CustomBusinessDay offset从datetime中减去

时间:2016-02-15 16:26:08

标签: python pandas calendar override offset

我有以下代码用于市场假期的自定义偏移类。出于某种原因,虽然我不能减去偏移量。添加工作正常。有人可以发现错误吗?

from pandas.tseries.offsets import CustomBusinessDay
from pandas.tseries.holiday import get_calendar, HolidayCalendarFactory, GoodFriday


class Holiday_offset:
'''
    creates an offset for market holidays so that the object that is returned
    may be added or subtracted to a datetime object to move 1 day forward or 
    back account for holidays and business days.
'''
def __init__(self):
    self.cal = get_calendar('USFederalHolidayCalendar')  # Create calendar instance
    self.cal.rules.pop(7)                                # Remove Veteran's Day rule
    self.cal.rules.pop(6)                                # Remove Columbus Day rule
    self.tradingCal = HolidayCalendarFactory('TradingCalendar', self.cal, GoodFriday)

    #new instance of class return as an offset object 
    self.offset = CustomBusinessDay(calendar=self.tradingCal())
def __add__(self,other):
    return self.offset + other
def __radd__(self,other):
    return self.offset + other
def __iadd__(self,other):
    return self.offset + other
def __sub__(self,other):
    return self.offset - other
def __rsub__(self,other):
    return self.offset - other
def __isub__(self,other):
    return self.offset - other
def __index__(self,other):



TypeError: Cannot subtract datetime from offset

1 个答案:

答案 0 :(得分:0)

这可能有点哈哈,但我更改了以下内容:

from pandas.tseries.offsets import CustomBusinessDay, BDay


def __sub__(self,other):
    other-= BDay()
    while self.is_holiday(other):
        other -= BDay()
    return other
def __rsub__(self,other):
    return self.__sub__(other)
def __isub__(self,other):
    return self.__sub__(other)