0

how to add hours in python? in the format below:

hour1= '20:00'
hour2= '25:00' 
sum= hour1 + hour2

so the correct print and formatted as I want it would be: result of the sum 45:00:00

1 Answers1

0

I just copied and edited this answer:

import datetime

# for show hours use below format
timeList = ['25:00:00', '20:00:00']
mysum = datetime.timedelta()
for i in timeList:
    (h, m, s) = i.split(':')
    d = datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))
    mysum += d
print(str(mysum))

sad
  • 89
  • 1
  • 4
  • `NameError: name 'h' is not defined`. You introduced errors while copying the original answer, and didn't take the time to test the code. Note that the OP wanted hours and minutes, not minutes and seconds, and he stated that his expected output was "45:00", which you can't get by printing timedelta objects: hours over 24 get converted to days. – Thierry Lathuille Mar 12 '22 at 16:17
  • excuse me, edited answer: add `hours` to datetime.timedelta – sad Mar 12 '22 at 16:22
  • Maybe i misunderstood the question but the code works. when the result gets over 24 converts to day. – sad Mar 12 '22 at 16:31
  • You're still adding minutes and seconds instead of hours and minutes. Try it with `timeList = ['25:00:00', '20:00:00']` and see how this doesn't give the expected output. Note that the OP asked about adding *hours*, and provided an expected output in HH:MM:SS format, which seems to indicate that the inputs would be in HH:MM format. – Thierry Lathuille Mar 12 '22 at 16:40
  • @ThierryLathuille you right, the answer is totally wrong based on what Rafael asked. how about i delete this answer? – sad Mar 12 '22 at 16:47
  • That's probably the thing to do in this case, there's no simple way to make use of `datetime` here... It would also probably be good to wait for the OP to answer the question about the discrepancy between his input and output format... – Thierry Lathuille Mar 12 '22 at 16:53