簡體   English   中英

在 Python 中查找一周的最后一個工作日

[英]Find last business day of the week in Python

我們可以執行以下操作來獲取當月的最后一個工作日:

from pandas.tseries.offsets import CBMonthEnd
from datetime import datetime, date

last_busday_month = BMonthEnd().rollforward(current_date).date()

或使用自定義假期日歷:

last_busday_month = CBMonthEnd(holidays=holidays).rollforward(current_date).date()

我怎樣才能在一周的最后一個工作日實現同樣的目標?

不像熊貓方法那么整潔,但這個方法對我有用:

import pandas as pd

from datetime import datetime
from pandas.tseries import offsets
from pandas.tseries.holiday import USFederalHolidayCalendar as calendar


def check_holidays(start_of_week, end_of_week, holidays ):
    if end_of_week in holidays:
        if end_of_week == start_of_week:
            print('There are no business days this week')
            return None

        end_of_week = (end_of_week - offsets.Day(1))
        end_of_week = check_holidays(start_of_week, end_of_week, holidays)
    return end_of_week


def BWeekEnd(current_date, holidays=None, friday=4, startdate='2019-01-01', enddate='2019-12-31'):
    current_date = datetime.strptime(current_date.isoformat()[:10], '%Y-%m-%d')  # round time to 00:00:00
    start_of_week  = (current_date - offsets.Day(current_date.weekday(), normalize=True))
    end_of_week = (current_date + offsets.Day(friday - current_date.weekday(), normalize=True))

    if not holidays:
        cal = calendar()
        holidays = cal.holidays(start=startdate, end=enddate)

    end_of_week = check_holidays(start_of_week, end_of_week, holidays)

    if end_of_week:
        return end_of_week.date()
    else:
        return None


current_date = datetime.today()
BWeekEnd(current_date, holidays=[pd.to_datetime('2019-03-01'), 
                                 pd.to_datetime('2019-02-28'), 
                                 pd.to_datetime('2019-02-27'), 
                                 pd.to_datetime('2019-02-26'),
                                 pd.to_datetime('2019-02-25')])
import pandas as pd

# Given the monday on the week that you would to get the last business day
monday='2020-04-06'
t=pd.date_range(pd.Timestamp(end_date), 
pd.Timestamp(end_date)+pd.Timedelta('7 days'),freq='W-MON')
last_day_on_week = t[-1]-pd.offsets.BDay(1)
print (last_day_on_week.strftime('%Y-%m-%d'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM