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

时间:2019-02-28 12:59:27

标签: python python-3.x pandas datetime

我们可以执行以下操作以获得该月的最后一个工作日:

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

如何在一周的最后一个工作日达到相同的目标?

2 个答案:

答案 0 :(得分:0)

不像熊猫方法那么整洁,但这对我有用:

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

答案 1 :(得分:0)

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