一个简单的数学运算python

时间:2016-11-06 18:07:49

标签: python python-2.7 python-3.x math

我有一个方法可以返回指定范围内的天数,并且不包括星期五等特定日期。这是一个例子,如果你从2016年8月6日到2016年6月6日星期五和星期四,结果将是8天假期和24个工作日。如果我想要进行相反的操作,如果我只有工作日和开始日期,我如何找到结束日期(2016-9-6)。

from datetime import datetime, timedelta

def measure_workingdays(start_date, end_date, off_days):
    format = "%Y-%m-%d"
    if not isinstance(start_date, datetime):
        start_date = datetime.strptime(start_date, format)
    if not isinstance(end_date, datetime):
        end_date = datetime.strptime(end_date, format)
    total_days = (end_date - start_date).days + 1 # + 1 Because it count one day less
    holiday = 0
    start = start_date
    for rec in range(total_days):
        day = start.strftime("%a")
        if day in off_days:
            holiday += 1
        start += timedelta(days=1)
    print(holiday) # 8
    working_days = total_days - holiday
    print(working_days) # 24


start_date = "2016-8-6"
start_date = datetime.strptime(start_date, "%Y-%m-%d")
end_date = "2016-9-6"
end_date = datetime.strptime(end_date, "%Y-%m-%d")
off_day = ['Fri','Thu']

working_days = measure_weekdays(start_date, end_date, off_day)

反向操作示例

def measure_weekdays_reverse(start_date, paid, off_days):
    format = "%Y-%m-%d"
    if not isinstance(start_date, datetime):
        start_date = datetime.strptime(start_date, format)
    holiday = 0
    start = start_date
    for rec in range(paid):
        day = start.strftime("%a")
        if day in off_days:
            holiday += 1
        start += timedelta(days=1)
    print(holiday) # Output 6 instead of 8
    last_paid_date = start + timedelta(days=holiday)
    print(last_paid_date) # output 2016-09-05 insteaad of 2016-09-06

total_days = measure_weekdays_reverse(start_date, 24, ["Fri","Thu"])

1 个答案:

答案 0 :(得分:0)

错误是你只循环修复次数(付费天数),所以如果你遇到假期,你实际上不会迭代到足以找到所有真正的付费天数,这可能仍然会隐藏一些假期

您可以通过在假期添加内循环来解决此问题。改变这个:

for rec in range(paid):
    day = start.strftime("%a")
    if day in off_days:
        holiday += 1
    start += timedelta(days=1)
print(holiday) # Output 6 instead of 8
last_paid_date = start + timedelta(days=holiday)

到此:

for rec in range(paid):
    day = start.strftime("%a")
    while day in off_days:
        holiday += 1
        start += timedelta(days=1)
        day = start.strftime("%a")
    last_paid_date = start
    start += timedelta(days=1)
print(holiday)