如何在日期中添加不包括节假日的工作日

2024-04-23 22:39:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧(df),其中包含开始日期列和添加日期列(=10)。我想创建目标日期(=start_date + add_days),不包括周末和假日(假日作为数据帧)

我做了一些研究,我尝试了这个

from datetime import date,  timedelta
import datetime as dt

df["star_date"] = pd.to_datetime(df["star_date"])
Holidays['Date_holi'] = pd.to_datetime(Holidays['Date_holi'])


def date_by_adding_business_days(from_date, add_days, holidays):
    business_days_to_add = add_days
    current_date = from_date
    while business_days_to_add > 0:
        current_date += datetime.timedelta(days=1)
        weekday = current_date.weekday()
        if weekday >= 5: # sunday = 6
            continue
        if current_date in holidays:
            continue
        business_days_to_add -= 1
    return current_date


#demo:
base["Target_date"]=date_by_adding_business_days(df["start_date"], 10, Holidays['Date_holi'])

但我得到了这个错误:

AttributeError: 'Series' object has no attribute 'weekday'

谢谢你的帮助


Tags: to数据fromadddfdatetimedateholidays
1条回答
网友
1楼 · 发布于 2024-04-23 22:39:34

ALollz的评论非常有效;在创建过程中自定义日期,以便只保留针对您的问题定义的工作日,这将是最佳选择

但是,我假设您不能预先定义工作日,您需要使用按原样构建的数据框架来解决问题

以下是一种可能的解决方案:

import pandas as pd
import numpy as np
from datetime import timedelta

# Goal is to offset a start date by N business days (weekday + not a holiday)

# Here we fake the dataset as it was not provided
num_row = 1000
df = pd.DataFrame()
df['start_date'] = pd.date_range(start='1/1/1979', periods=num_row, freq='D')
df['add_days'] = pd.Series([10]*num_row)

# Define what is a week day
week_day = [0,1,2,3,4] # Monday to Friday
# Define what is a holiday with month and day without year (you can add more)
holidays = ['10-30','12-24'] 

def add_days_to_business_day(df, week_day, holidays, increment=10):
    '''
       modify the dataframe to increment only the days that are part of a weekday
       and not part of a pre-defined holiday
       >>> add_days_to_business_day(df, [0,1,2,3,4], ['10-31','12-31'])
           this will increment by 10 the days from Monday to Friday excluding Halloween and new year-eve
    '''
    # Increment everything that is in a business day
    df.loc[df['start_date'].dt.dayofweek.isin(week_day),'target_date'] = df['start_date'] + timedelta(days=increment)
    # Remove every increment done on a holiday
    df.loc[df['start_date'].dt.strftime('%m-%d').isin(holidays), 'target_date'] = np.datetime64('NaT')


add_days_to_business_day(df, week_day, holidays)
df

注意:我没有使用“添加天数”列,因为它只是一个重复值。相反,我为函数increment使用了一个参数,它将增加N天数(默认值为N=10)

希望有帮助

相关问题 更多 >