每隔一个周末返回True,任何其他日子返回False

时间:2016-08-03 20:15:38

标签: python

我试图创建一个每隔一个周末运行的脚本,我已尝试使用datetime(我在互联网上找到的解决方案,同样),但它总是打印整周。

from datetime import date, timedelta
reference_monday = date(2016, 1, 8)        # any monday of a "week one"

schedule = [[True, True, True, True, True, True, True],
            [True, True, True, True, True, False, False]]

def check_date(d):
    return schedule[abs(d - reference_monday).days / 7 % 2][d.weekday()]

start = date(2012, 6, 4)

for w in range(6):
    thisweek = start + timedelta(weeks=w)
    print 'week of', thisweek, ':',
    print ','.join(str(check_date(thisweek + timedelta(days=d))) for d in range(7))

它返回

week of 2012-06-04 : True,True,True,True,True,True,True
week of 2012-06-11 : True,True,True,True,True,False,False
week of 2012-06-18 : True,True,True,True,True,True,True
week of 2012-06-25 : True,True,True,True,True,False,False
week of 2012-07-02 : True,True,True,True,True,True,True
week of 2012-07-09 : True,True,True,True,True,False,False

我希望它返回true或false,具体取决于当天。

1 个答案:

答案 0 :(得分:0)

如评论中所述,有更好的替代方案来安排任务。

这是你想要的吗?

def check_date(d):
    return not schedule[abs(d - reference_monday).days / 7 % 2][d.weekday()]

输出

week of 2012-06-04 : False,False,False,False,False,False,False
week of 2012-06-11 : False,False,False,False,False,True,True
week of 2012-06-18 : False,False,False,False,False,False,False
week of 2012-06-25 : False,False,False,False,False,True,True
week of 2012-07-02 : False,False,False,False,False,False,False
week of 2012-07-09 : False,False,False,False,False,True,True
  

我希望它返回true或false,具体取决于当天

start = date(2012, 6, 4)
for w in range(6):
    thisweek = start + timedelta(weeks=w)
    print 'week of', thisweek, ':',

    # Only Saturday and Sunday
    run_sat = check_date(thisweek + timedelta(days=5))
    run_sun = check_date(thisweek + timedelta(days=6))

    print "{:5} | {:5}".format(str(run_sat), str(run_sun))

输出

week of 2012-06-04 : False | False
week of 2012-06-11 : True  | True 
week of 2012-06-18 : False | False
week of 2012-06-25 : True  | True 
week of 2012-07-02 : False | False
week of 2012-07-09 : True  | True