简体   繁体   English

在 Python 中不包括周末的 x 天前的日期

[英]What date it was x amount of days ago excluding weekends in Python

As an example I want to see what the date would be if it was today - 6 days.作为一个例子,我想看看如果今天是什么日期 - 6 天。 However, I only want to count days that are weekdays.但是,我只想计算工作日的天数。 So given 8/22 the output should be 8/12 as that is 6 business days only.因此,鉴于 8/22,output 应该是 8/12,因为这只是 6 个工作日。

Tried using the weekday function to return if it is a 5 or 6 for saturday and sunday and skipping those days but I am not having luck so far尝试使用工作日 function 返回周六和周日的 5 或 6 并跳过那些日子,但到目前为止我没有运气

Current code:当前代码:

from datetime import datetime, timedelta

age = 6
counter = 0
difference = datetime.today() - timedelta(counter)

while counter <= age:
difference = datetime.today() - timedelta(counter)
counter = counter + 1

this code only returns the day with the weekends included as I haven't been able to figure out how to exclude the weekend.此代码仅返回包含周末的那一天,因为我无法弄清楚如何排除周末。 I set up the code to loop to check if it is a 5 or 6 using the weekday() function but I keep getting bad results when attempting that我将代码设置为循环以使用 weekday() function 检查它是 5 还是 6,但是在尝试这样做时我一直得到不好的结果

You can calculate the actual days difference by calculating the number of weekends past, and subtracting the date by the days difference and the days in weekend to get the result.您可以通过计算过去的周末数来计算实际天数差异,然后将日期减去天数差异和周末天数得到结果。

from datetime import datetime,timedelta
from math import ceil

def subtract_weekdays (from_date, diff): 
    no_of_weekends = ceil((diff - from_date.weekday())/5)
    result_date = from_date - timedelta(days=diff + no_of_weekends * 2)
    return result_date

print subtract_weekdays(datetime.today(), 6)
from datetime import date, timedelta
    

def weekdays_between(startdate,stopdate):
    day = startdate
    daycount = 0
    while day < stopdate :
    if day.weekday() < 5 :
        daycount += 1
    day = day + timedelta(days=1)
            
    return daycount
        
if __name__ == "__main__" :
    day=date.today()
    dayn=day + timedelta(days=45)
    print(weekdays_between(day,dayn))
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM