1

How do I sum timedeltas in a loop? If I add the timedeltas manually the sum is correct. But if I use a while loop to sum the timedeltas I get this error:

TypeError: can only concatenate str (not "datetime.timedelta") to str

And the other question is, if the sum value is over 24 hours- python prints sum as one day and x hours. I need the sum value for example in 26:15 (26hours and 15 minutes).

import datetime

fmt = '%H%M'
start = [];end = [];td = []

start.append( datetime.datetime.strptime('0300', fmt) )
start.append( datetime.datetime.strptime('0645', fmt) )

end.append( datetime.datetime.strptime('1505', fmt) )
end.append( datetime.datetime.strptime('1845', fmt) )

td.append( end[0] - start[0] )
td.append( end[1] - start[1] )

print('timedelta1= ' + str(td[0]))
print('timedelta2= ' + str(td[1]))

tSum = td[0] +td[1]
print( 'Sum: ' + str(tSum) )

tSumLoop = ''
i = 0
while i < 2:
    tSumLoop += td[i]
    i += 1
print(tSumLoop)

How do I solve these two problems? Thanks for your help!

InFlames82
  • 493
  • 6
  • 17

2 Answers2

1

You initialize the sum with an empty string:

tSumLoop = ''
i = 0
while i < 2:
    tSumLoop += td[i]
    i += 1

Therefore you cannot add a timedelta to it.

You could initialize it with the first timedelta and add the remaining ones in a loop:

tSumLoop = td[0]
i = 1
while i < 2:
    tSumLoop += td[i]
    i += 1

There are various better ways to express this loop, but you may have your reasons to not use them:

tSumLoop = td[0]
for i in range(1, 2):
    tSumLoop += td[i]

Or

tSumLoop = td[0]
for delta in td[1:]:
    tSumLoop += delta

Or

tSumLoop = sum(td[1:], td[0])

Starting with a zero timedelta (see Andrej Kesely's answer) has the advantage that it also works if td is empty.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
1

You can use start value as zero timedelta: datetime.timedelta(0):

tSumLoop = datetime.timedelta(0)
i = 0
while i < 2:
    tSumLoop += td[i]
    i += 1
print(tSumLoop)

Or use sum():

tSum = sum(td, datetime.timedelta(0))
print( 'Sum:', tSum )

Prints:

Sum: 1 day, 0:05:00

EDIT: To format the sum, you can use (based on https://stackoverflow.com/a/62719270/10035985)

def period(delta, pattern):
    d = {}
    d['h'], rem = divmod(delta.total_seconds(), 3600)
    d['m'], d['s'] = divmod(rem, 60)
    return pattern.format(**d)

tSum = sum(td, datetime.timedelta(0))
print(period(tSum, '{h:>02.0f}:{m:>02.0f}'))

Prints:

24:05
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91