Home > front end >  Getting the error AttributeError: 'datetime.datetime' object has no attribute 'timede
Getting the error AttributeError: 'datetime.datetime' object has no attribute 'timede

Time:09-17

I want to get the total of times by doing this inner for loop...However it seems like I am doing something wrong here, because I am getting the error AttributeError: 'datetime.datetime' object has no attribute 'timedelta'...

from datetime import datetime, timedelta
N = int(input())
lista = []
for n in range(N):
    name = input()
    times = [datetime.strptime(m, '%S.%f') for m in input().split()]
    initialTime = datetime(1900,1,1,0,0,0)
    for m in times:
        initialTime  = initialTime.timedelta(m)
    lista.append(initialTime)
print(lista)

I am also giving you some sample data:

5
Guilherme
20.252 20.654 20.602
Edison
24.000 24.024 23.982
Caetano
20.380 25.816 21.739
Geraldo
20.310 25.725 21.664
Luis
20.289 25.699 21.643

Which is intended to display the following result

["1:01.508", "1:12.006", "1:07.935", "1:07.699", "1:07.631"]

CodePudding user response:

It looks to me like you are trying to add up three "lap" times to get a total time for each entry. For that, you don't need initialTime at all. You can convert all the time entries to timedelta objects and use sum() to add them up.

Inside your outer loop:

times = input().split()
for i in range(len(times)):
    t = datetime.strptime(times[i], '%S.%f')
    times[i] = timedelta(minutes=t.minute, seconds=t.second, microseconds=t.microsecond)
lista.append(sum(times, timedelta()))

The output will be a list of timedelta objects. They can be easily converted to strings with str() if needed.

  • Related