Valentin Weber
Valentin Weber

Reputation: 13

Why does the duration between Datetime and Timedelta come up 1h short?

I'm trying to automate documenting my worktimes and need a way to get the duration between the starting and ending time. During my research I came upon this question which seemed to provide a solution to my problem.

However, when trying to get the duration between "11:30" and "12:30" the datetime.time() method returns "00:00:00" and I have no idea why.

This is the code I'm using.

from datetime import datetime, timedelta
from time import strptime

start = strptime("11:30", "%H:%M")
stop = strptime("12:30", "%H:%M")

start_dt = datetime(100, 1, 1, start.tm_hour, start.tm_min)

duration = start_dt + timedelta(hours=stop.tm_hour,
                                minutes=stop.tm_min,
                                seconds=0)

print(duration.time())

This is my expected (desired) output: 01:00:00

This is the actual output I'm getting: 00:00:00

I was wondering whether it had something to do with the time.strptime() method I'm using to get hour and minute values so I tried this as well:

from datetime import datetime, timedelta

start_dt = datetime(100, 1, 1, 11, 30)

duration = start_dt + timedelta(hours=12,
                                minutes=30,
                                seconds=0)

print(duration.time())

The output remains the same. Does anyone know why? I'm completely at a loss. Any help would be appreciated.

Upvotes: 1

Views: 53

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

Short answer: you added up the two times whereas for a duration, you need to calculate the difference.

Because you added the two up. Indeed, your start_dt looks like: 1-1-100 11:30, and you added 12:30 to that, so that means that:

start_dt   1-1-100  11:30
+                   12:30
-------------------------
           2-1-100  00:00

or midnight, the next day.

If you want to calculate the time difference, you can subtract the two, like:

start = datetime.strptime('11:30', '%H:%M')
stop = datetime.strptime('12:30', '%H:%M')
duration = stop - start  # minus (-), not plus (+)

this gives us then:

>>> duration
datetime.timedelta(0, 3600)
>>> str(duration)
'1:00:00'

so 3600 seconds, or one hour.

That being said, time is quite ambiguous, since it is timezone specific: dependong on where you are, and when (since some countries changed timezones), it can result in totally different results.

Upvotes: 1

Related Questions