Skip to main content
 首页 » 编程设计

python之递增日期同时忽略周末

2025年05月04日16think

我目前正在为我的工作场所编写支持轮值表。

代码本身很简单

import itertools 
 
names = ["P1", "P2", "P3"] 
 
extns = {'P1': 'xxxx', 'P2': 'xxxy', 'P3': 'xxyy'} 
 
for _ in itertools.repeat(None, 5): 
    for name in names: 
        print name + " | " + extns[name] 

(名称替换为 Pn,数字替换为“x/y”替换)

到目前为止这很好用并且给了我预期的输出

P1 | xxxx 
P2 | xxxy 
P3 | xxyy 

重复5次。

但是期望的输出是

| <Todays Date> | P1 | xxxx | 

显然,我可以只使用日历库并使用那里的数据,然后对明天的日期等执行 today+1 之类的操作。

尝试跳过周末时出现问题。

每周工作 5 天意味着我们不在周末分配支持(周六/周日 0000-2400)

例如,9 月 1 日是星期一,所以我希望日期是

01-09-14 
02-09-14 
03-09-14 
04-09-14 
05-09-14 
08-09-14 
09-09-14 

如您所见,它会跳过 6 号和 7 号,因为那是周六和周日。

我查看了 calendar 模块并找到了以下代码:

calendar.setfirstday() 

这听起来很有希望,我也可以使用

iterweekdays() 

返回工作日的迭代器。

我不确定如果我要遍历它是否会给出日期。我也不确定我将如何实际遍历它。

编辑:

下面是预期的输出:

| 10-09-14 | P1 | xxxx |  
| 11-09-14 | P2 | xxxy |  
| 12-09-14 | P3 | xxyy |  
| 15-09-14 | P1 | xxxx |  
| 16-09-14 | P2 | xxxy |  
| 17-09-14 | P3 | xxyy |  
| 18-09-14 | P1 | xxxx |   
| 19-09-14 | P2 | xxxy |  
| 22-09-14 | P3 | xxxy |  
| 23-09-14 | P1 | xxxx |  
| 24-09-14 | P2 | xxxy |  
| 25-09-14 | P3 | xxyy |  
| 26-09-14 | P1 | xxxx |  
| 29-09-14 | P2 | xxxy |  
| 30-09-14 | P3 | xxyy |  

目前我可以获得今天的日期并检查它是否是工作日。那么问题是及时进行。

请您参考如下方法:

您可以简单地使用 datetime 及其 .weekday() 函数将一周中的几天映射到 0-6,从星期一 = 0 开始到星期日 = 结束6.

from datetime import datetime 
 
today = datetime.today()  # get todays datetime 
 
if not today.weekday() == 5 or today.weekday == 6:   # if we no weekend-day 
 
    print(datetime.strftime(today,'%d-%m-%y')) # format it to day-month-year