如果日期是周末-自动重新运行该功能

时间:2018-09-29 00:28:51

标签: python

因此,我可以根据给定的开始日期与结束日期之间的关系生成随机的日期,但是,如果该日期恰好是一个周末-当前,我所能做的就是向用户打印“这是一个周末”。我想做的是,如果随机日是周末,请重新运行该功能,这样用户就不必手动进行操作。基本上-仅打印工作日-当前,如果随机日是周末,它将打印空白或None值。主要目标是仅在工作日退货/打印。

这是到目前为止的代码:

from datetime import datetime, timedelta
from random import randrange

def random_date(start, end):
    delta = end - start
    random_day = randrange(delta.days)
    myresult = start + timedelta(days=random_day)
    return myresult

d1 = datetime.strptime('9/1/2018', '%m/%d/%Y')
d2 = datetime.strptime('9/30/2018', '%m/%d/%Y')
myresult = random_date(d1, d2)

if myresult.weekday() not in (5, 6):
    print myresult.strftime('%m-%d-%Y')
else:
    print "hit a weekend"

2 个答案:

答案 0 :(得分:1)

一个选项:

def random_weekday(start, end):
    date = None

    while (not date or date.weekday() in (5, 6)):
        days = randrange((end - start).days)
        date = start + timedelta(days=days)

    return date

start = datetime.strptime('9/1/2018', '%m/%d/%Y')
end = datetime.strptime('9/30/2018', '%m/%d/%Y')

for i in range(20):
  print(random_weekday(start, end).strftime('%m-%d-%Y'))

答案 1 :(得分:0)

因此,您需要使用while循环来获取日期,直到得到不是周末的日期为止,如下所示:

from datetime import datetime
from random import randrange
from datetime import timedelta

def random_date(start, end):
    delta = end - start
    random_day = randrange(delta.days)
    myresult = start + timedelta(days=random_day)
    return myresult

    while True:

        d1 = datetime.strptime('9/1/2018', '%m/%d/%Y')
        d2 = datetime.strptime('9/30/2018', '%m/%d/%Y')
        myresult = random_date(d1, d2)

        if myresult.weekday() not in (5,6):
            break

    print myresult.strftime('%m-%d-%Y')