在Python中,我想从一个时间段内减去一个时间段

In Python, I want to subtract a time period from within a time period

我想计算一天的工作时间,并从中减去午餐时间。所以有人在 8:00 打卡,从 12:00 吃午饭到 12:30,然后在 16:00 结束。 午餐时间在设置 table 中配置,具有开始时间和结束时间。

简而言之,我想计算一下:

结束时间减去开始时间 = n hours:minutes 工作减去午餐时间(= 12:30 - 12:00 = 30 分钟)

如何在 Python 中进行计算而不将其硬编码? 非常感谢帮助

干杯

你可以用 Python datetime:

import datetime as dt

def work_time(start, end, lunch=[], format_='%H:%M'):
    """ Calculate the hours worked in a day.
    """
    start_dt = dt.datetime.strptime(start, format_)
    end_dt = dt.datetime.strptime(end, format_)

    if lunch:
        lunch_start_dt = dt.datetime.strptime(lunch[0], format_)
        lunch_end_dt = dt.datetime.strptime(lunch[1], format_)
        lunch_duration = lunch_end_dt - lunch_start_dt
    else:
        lunch_duration = dt.timedelta(0)

    elapsed = end_dt - start_dt - lunch_duration
    hours = elapsed.seconds / 3600

    return hours
>>> work_time('8:00', '16:00', lunch=['12:00', '12:30'])
7.5

日期时间的 documentation 提供了有关特定格式以及如何使用时间增量对日期时间和时间对象执行操作的更多信息。