python最后一个工作日(使用CustomBusinessDay)?

时间:2018-04-03 07:03:41

标签: python pandas datetime

我想计算特定日期之前或之后的最后一个工作日(包括假期,而不仅仅是周末)?

<div class="wrapper">
  <div class="navigation">NAVIGATION</div>
  <div class="container">
    <div class="chat-list">CHAT LIST</div>
    <div class="chats">CHATS</div>
    <div class="chat-profile">CHAT_PROFILE</div>
  </div>
</div>

这是在耶稣受难日,假期(如图所示)......应该在= 2018-03-29之前显示...

问题是什么?

1 个答案:

答案 0 :(得分:2)

我能够重现这个问题,经过一些测试后我将其缩小为使用DatetimeIndex作为CustomBusinessDay中日历参数的输入。

您可以跳过它并直接使用日历实例:

import datetime as dt
import pandas as pd
from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, nearest_workday, \
    USMartinLutherKingJr, USPresidentsDay, GoodFriday, USMemorialDay, \
    USLaborDay, USThanksgivingDay
from pandas.tseries.offsets import CustomBusinessDay, BDay

class USTradingCalendar(AbstractHolidayCalendar):
    rules = [
        Holiday('NewYearsDay', month=1, day=1, observance=nearest_workday),
        USMartinLutherKingJr,
        USPresidentsDay,
        GoodFriday,
        USMemorialDay,
        Holiday('USIndependenceDay', month=7, day=4, observance=nearest_workday),
        USLaborDay,
        USThanksgivingDay,
        Holiday('Christmas', month=12, day=25, observance=nearest_workday)
    ]

bday_us = CustomBusinessDay(calendar=USTradingCalendar())

d = dt.datetime(2018, 3, 31)

c = d - bday_us

print(c)

输出:

2018-03-29 00:00:00