Loop through dates except for weekends

后端 未结 3 739
生来不讨喜
生来不讨喜 2020-12-15 10:28

So I have a script that has date arguments for different functions and I want it to loop through 01-01-2012 to 06-09-2012 not including weekends. I

3条回答
  •  生来不讨喜
    2020-12-15 11:11

    Use the datetime.weekday() method. It returns values between zero and six, related to the weekdays. Saturday value is 5 and Sunday value is 6; so, if you skip the operation when these values appear, you skip weekdends:

    start = datetime(2012, 1, 1)
    end = datetime(2012, 10, 6)
    delta = timedelta(days=1)
    d = start
    diff = 0
    weekend = set([5, 6])
    while d <= end:
        if d.weekday() not in weekend:
            diff += 1
        d += delta
    

提交回复
热议问题