Python 熊猫:如果日期是周日或周六,如何将周五作为工作日返回?

Python 熊猫:如果日期是周日或周六,如何将周五作为工作日返回?,python,pandas,Python,Pandas,如果我的日期是周六或周日,我会尝试返回工作日日期。下面是代码,但似乎不完整。请建议 import holidays import datetime enter_date = '2020-10-30' enter_date = pd.to_datetime(enter_date) before_date = enter_date - datetime.timedelta(days=5) print(before_date) 使用pd.DatetimeIndex.dayofweek属性(请参阅)

如果我的日期是周六或周日,我会尝试返回工作日日期。下面是代码,但似乎不完整。请建议

import holidays
import datetime

enter_date = '2020-10-30'
enter_date = pd.to_datetime(enter_date)
before_date = enter_date - datetime.timedelta(days=5)
print(before_date)

使用
pd.DatetimeIndex.dayofweek
属性(请参阅)。它将一周中从周一到周日的每一天映射到
范围(7)

例如:

import pandas as pd


saturday = pd.to_datetime('2020-12-12')
sunday = pd.to_datetime('2020-12-13')

def func(date):
    if date.dayofweek == 5: 
        date = date - pd.Timedelta('1 day')  # SATURDAY
    elif date.dayofweek == 6: 
        date = date - pd.Timedelta('2 day')  # SUNDAY
    return date


print(func(saturday))  # 2020-12-11 00:00:00
print(func(sunday))  # 2020-12-11 00:00:00

我认为您正在寻找一种解决假日和周末问题的解决方案

看看这是否解决了你的问题

不带熊猫的解决方案(用于循环和日期时间) 其结果如下:

Given date : 2020-12-09 is a Wednesday
The business working day is 2020-12-09 and is a Wednesday

Given date : 2020-12-12 is a Saturday
The business working day is 2020-12-11 and is a Friday

Given date : 2020-12-25 is a Friday
The business working day is 2020-12-24 and is a Thursday

Given date : 2020-12-27 is a Sunday
The business working day is 2020-12-24 and is a Thursday

Given date : 2021-01-18 is a Monday
The business working day is 2021-01-15 and is a Friday
请注意:

  • 2020年9月12日是星期三,未做任何更改
  • 2020年12月12日是星期六,改为2020年12月11日星期五
  • 2020年12月25日是星期五和假日。更改为2020年12月24日 星期四
  • 2020年12月27日为周日,2020年12月25日为周五,但为假日。是的 更改为2020年12月24日星期四
  • 2021年1月18日是星期一和假日。更改为2021年1月15日 星期五
包括熊猫在内的解决方案 以下是一个包括熊猫在内的解决方案:

from datetime import datetime, timedelta
import calendar, holidays
import pandas as pd

def business_day(enter_date):
    while enter_date in holidays.US() or enter_date.weekday() > 4:
        enter_date = enter_date - timedelta(days=1)

    return enter_date

df = pd.DataFrame({'enter_date':['2020-12-09','2020-12-12','2020-12-25', '2020-12-27','2021-01-18']})
df['enter_date'] = pd.to_datetime(df['enter_date'])
df['business_date'] = df['enter_date'].apply(lambda x: business_day(x))
print (df)
其输出将为:

  enter_date business_date
0 2020-12-09    2020-12-09
1 2020-12-12    2020-12-11
2 2020-12-25    2020-12-24
3 2020-12-27    2020-12-24
4 2021-01-18    2021-01-15

如果您仍然需要使用pandas的解决方案,请告诉我。您不是想
将熊猫导入为pd
而不是
导入假日
  enter_date business_date
0 2020-12-09    2020-12-09
1 2020-12-12    2020-12-11
2 2020-12-25    2020-12-24
3 2020-12-27    2020-12-24
4 2021-01-18    2021-01-15