Ketan Chauhan
Ketan Chauhan

Reputation: 173

How to get hours value greater than 24 hours in python 2.7?

time1 = timedelta(days=2, hours=6.20)
time2 = timedelta(hours=20.10)
sum_time = time1 + time2
print str(sum_time)
print sum_time.total_seconds() / 3600

Output:

3 days, 2:18:00
74.3

How to get output 74:18:00 ?

Upvotes: 2

Views: 109

Answers (1)

jps
jps

Reputation: 22525

With total_Seconds / 3600 you only get the hours in decimal format.

You can use divmod to break down the seconds into full hours, minutes and seconds:

divmod(a, b)

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division

The code would look like this (I added 34 seconds in time2 to check if the seconds part is correct):

from datetime import timedelta
time1 = timedelta(days=2, hours=6.20)
time2 = timedelta(hours=20.10, seconds=34)
sum_time = time1 + time2
print str(sum_time)
hours, seconds = divmod(sum_time.total_seconds(), 3600)
minutes,  seconds = divmod(seconds, 60)
print "%d:%02d:%02d" % (hours, minutes, seconds)

and the output will be:

3 days, 2:18:34
74:18:34

The result of the first divmod is 74 hours (quotient) and a remainder of 1114 seconds. The second divmod is feeded with the remaining seconds from the line before (1114) and gives a result of 18 minutes and 34 seconds.

Upvotes: 2

Related Questions