在时间计算中显示负时数?

show negative hours with time calculations?

有没有办法显示负时数? 例如: 如果用户签入和签出并且工作了 3 小时,但他应该至少工作 4 小时,则计算 (3 - 4) 应该得到 -1 小时 (-01:00)。 但是当我做这个计算时:

checkin = datetime.datetime(1, 1, 1, 8) # this is 0001-01-01 08:00:00
checkout = datetime.datetime(1, 1, 1, 11) # 0001-01-01 11:00:00

should_work = datetime.timedelta(hours=4)
has_worked = checkout - checkin # results in 03:00:00

result = has_worked - should_work # this results into "-1 day, 23:00:00" insted of "-01:00"

有没有其他库或日期时间函数可以处理这类事情?

timedelta 对象不太擅长显示格式。减去 1 天,加上 23 小时 -1 小时,但这很尴尬。由于有多种显示增量的方法(例如,您应该允许 25 小时,还是应该是一天?),您自己计算是正常的。这个只需要几小时和几分钟。多天以小时表示 >= 24.

import datetime

def timedelta_str(td):
    s = int(td.total_seconds())
    if s < 0:
        s = abs(s)
        neg = "-"
    else:
        neg = ""
    m, seconds = divmod(s, 60)
    hours, minutes = divmod(m, 60)
    return f"{neg}{hours:02d}:{minutes:02d}"

checkin = datetime.datetime(1, 1, 1, 8) # this is 0001-01-01 08:00:00
checkout = datetime.datetime(1, 1, 1, 11) # 0001-01-01 11:00:00

should_work = datetime.timedelta(hours=4)
has_worked = checkout - checkin # results in 03:00:00
result = has_worked - should_work

print('result', timedelta_str(result))