增加日期同时忽略周末

2024-09-28 19:21:02 发布

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

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

代码本身很简单

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”代替

到目前为止效果很好,并给出了

^{pr2}$

重复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 | 

目前我可以得到今天的日期,并检查它是否是一个工作日。那么问题就要及时解决了。在


Tags: 代码nameinfornamescalendaritertoolsp2
3条回答

您可以使用calendar的weekday,如果返回5或6,则可以将其视为周末。在

编辑: 可以使用datetime执行以下操作:

>>> import datetime
>>> d=datetime.date(2014,9,10)
>>> d.weekday()
2

您只需使用datetime及其.weekday()函数,该函数将一周中的几天映射到0-6,从monday=0开始,到sunday=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

这应该可以做到:

import itertools
from datetime import datetime, timedelta

names = ["P1", "P2", "P3"]
extns = {'P1': 'xxxx', 'P2': 'xxxy', 'P3': 'xxyy'}

for (day,name) in itertools.izip((day for day in (datetime.today()+timedelta(n) for n in itertools.count()) if day.weekday() not in (5,6)), (itertools.cycle(names))):
    print "| %s | %s | %s |" % (day.strftime("%d-%m-%y"), name, extns[name])

从今天开始计数并无限循环。我只假设这就是你想要的,因为你的原始代码是如何结构化的。如果你想在特定的时间范围内使用,请告诉我。在


编辑:根据评论,这应该只在今天+10天内打印出来。这可能有很多种方法可以完成,但通过这种方法,您可以轻松编辑您想要的天数,甚至可以一直编辑到今天: ^{pr2}$

相关问题 更多 >