【问题标题】:A simple mathematic Operation python一个简单的数学运算python
【发布时间】:2016-11-06 18:07:48
【问题描述】:

我有一个方法可以返回指定范围内的天数,不包括某些特定的日子,比如星期五。这是一个例子,如果你在星期五和星期四取出,从 2016 年 8 月 6 日到 2016 年 9 月 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"])

【问题讨论】:

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


    【解决方案1】:

    错误是你只循环了一个固定的次数(带薪天数),所以如果你遇到假期,你实际上将没有足够的迭代来找到所有真正的带薪天,这可能仍然隐藏了一些假期.

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

    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)
    

    【讨论】:

    • 确实,day 变量需要在两个循环中更新。我更正了代码并对其进行了测试。现在它打印 8。
    猜你喜欢
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    相关资源
    最近更新 更多