Python:计算特定时间段内的小时数

时间:2014-12-26 16:29:35

标签: python datetime

我正在制作一个计算我的工资的脚本,因为我们没有将计划发送出去。 我们确实在一些时间段内获得额外收入。

每小时我都会获得61.86 DKK,但在某段时间内我会赚取额外的钱,如下所示。 (为简单起见,我已经计算了24小时循环中的时间,因为我已经习惯了)

Weekdays (18:00 - 06:00) 12.20 DKK
Saturday (15:00 - 24:00) 21.65 DKK
Sunday (whole day)       24.50 DKK

我已经计算好了,如何计算额外的钱和每小时罚款。虽然我的问题是,如果我有一个工作守卫从20:00开始到第二天4:00结束,那么它会给我和错误。我有一个IF声明,如果小时超过18(这是我在工作日得到额外的时间),则会激活,然后我减去小时数18,得到,我需要多少小时才能赚取额外费用。

    if d2.isoweekday() <= 5: #If its a weekday
    if d2.hour >= 18:
        extra += ((d2.hour - 18) * weekdaySalary) + ((d2.minute / 60) * weekdaySalary)

我如何检测,确定特定时期之间的小时数?

就好像我必须约会

26-12-2014 17:00
27-12-2014 08:00

我需要一种方法来查看这些工作时间中有多少是在这段时间内(18:00-06:00)。 如何才能做到这一点? 这就像有两个不同的日期范围。 第1名 - 当我得到额外的时候。 2rd - 因为我实际工作的时候。

26-12-2014 17:00
18:00 - extra money period start here
   |
   |how do i get the time between these to points?
   |
06:00 - extra money period ends here
27-12-2014 08:00

它也可能像这样

26-12-2014 17:00
18:00 - extra money period start here
  |
  |how do i get the time between these to points?
  |
27-12-2014 04:00
06:00 - extra money period ends here

每个答案都受到高度赞赏,花了很多时间试图弄清楚没有真正的结果。

1 个答案:

答案 0 :(得分:1)

根据您提供的两个范围,假设它们是您的班次开始和结束时,以下将计算从班次开始到结束的工资,增加基本费率或基本费率加上基于时间的额外工资:

def calculate_ot(t1,t2):
    t1 = datetime.strptime(t1, "%d-%m-%Y %H:%M")
    t2 = datetime.strptime(t2, "%d-%m-%Y %H:%M")
    days = ((t2 - t1).days * 86400)
    hours, rem = divmod((t2 - t1).seconds + days, 3600)
    start_ot = datetime.strptime("18:00 {}".format(t1.date()), "%H:%M %Y-%m-%d")
    end_ot = datetime.strptime("06:00 {}".format(t2.date()), "%H:%M %Y-%m-%d")

    total_pay = 0
    for x in range(hours): # loop in total hour time difference
        # if we are within the range of extras pay increase by normal rate plus ot
        if start_ot <= t1 < end_ot and t1 < t2:
            total_pay += 62 # or 62.20 you have conflicting examples
        else:
            # else just add basic pay rate
            total_pay == 50
        t1 += timedelta(hours=1) # keep adding another hour
    return total_pay
相关问题