Manko
Manko

Reputation: 91

show negative hours with time calculations?

is there a way to show negative hours? for example: if a user checksin and checksout and has 3 hours worked but he should have worked for atleast 4 hours the calculation (3 - 4) should result into -1 hour (-01:00). but when i do this calculation:

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"

is there some other library or datetime function for this kind of things?

Upvotes: 0

Views: 52

Answers (1)

tdelaney
tdelaney

Reputation: 77407

The timedelta object isn't that good at display formats. Minus 1 day, plus 23 hours is -1 hour, but that's awkward. Since there are lots of ways to display deltas, (e.g., should you allow 25 hours, or should that be a day?), its normal to do the math yourself. This one just does hours and minutes. multiple days are expressed in hours >= 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))

Upvotes: 2

Related Questions