gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:01:00 29 4
gpt4 key购买 nike

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

import datetime as dt

from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, nearest_workday, \
USMartinLutherKingJr, USPresidentsDay, GoodFriday, USMemorialDay, \
USLaborDay, USThanksgivingDay


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)
]


def get_trading_close_holidays(fromyear, toyear):
inst = USTradingCalendar()

return inst.holidays(dt.datetime(fromyear-1, 12, 31), dt.datetime(toyear, 12, 31))

print(get_trading_close_holidays(2018,2018))

>> DatetimeIndex(['2018-01-01', '2018-01-15', '2018-02-19', '2018-03-30', '2018-05-28', '2018-07-04', '2018-09-03', '2018-11-22', '2018-12-25'], dtype='datetime64[ns]', freq=None)

import datetime as dt
from pandas.tseries.holiday import USFederalHolidayCalendar
bday_us = CustomBusinessDay(calendar=get_trading_close_holidays(2000,2050))
d = dt.datetime(2018, 3, 31)
d - bday_us

>> Timestamp('2018-03-30 00:00:00')

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

有什么问题吗?

最佳答案

我能够重现该问题,经过一些测试后,我将范围缩小为使用 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

关于python 每月最后一个工作日(使用 CustomBusinessDay)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49624124/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com