I have a program which grabs the drivers laptimes and writes them to a txt file.
output.txt looks like this:
00:01:26.102
00:01:15.618
00:01:15.096
00:01:14.792
00:01:14.532
00:01:25.083
00:01:25.497
00:01:17.809
00:01:19.364
00:01:18.935
00:01:18.076
00:01:18.111
00:01:22.086
00:01:20.500
00:01:18.167
00:01:18.268
00:01:18.373
00:01:17.950
00:01:17.944
I want to sum all the lap times and divide it by lap count(basically find the average of them). But i cant manage to sum them correctly. How can i do it?
>Solution :
You can use timedelta
import datetime as dt
def avg_time(lst:list):
n=len(lst)
print(n)
res=[]
for i in lst:
hour,minute,second =i.split(":")
second,milli=second.split(".")
res.append(dt.timedelta(hours=int(hour),minutes=int(minute),seconds=int(second),milliseconds=int(milli)))
return sum(res,res[0])/n
t = ["00:01:26.102","00:01:15.618","00:01:15.096","00:01:14.792","00:01:14.532","00:01:25.083","00:01:25.497","00:01:17.809","00:01:19.364",
"00:01:18.935","00:01:18.076","00:01:18.111","00:01:22.086","00:01:20.500","00:01:18.167","00:01:18.268","00:01:18.373","00:01:17.950","00:01:17.944",]
a = avg_time(t)
print(a)
Output:
0:01:23.600263
PS. you can not format timedelta like other datetime object. So you can use some normal Maths to get it as follows:
total_second=a.total_seconds()
hour_s,second_s=divmod(total_second,3600)
minute_s,second_s=divmod(second_s,60)