average time calculation??

MRAB python at mrabarnett.plus.com
Thu Jan 10 13:22:55 EST 2013


On 2013-01-10 17:50, pmec wrote:
> Hi there guys i've got a script that's suppose to find the average of two times as strings. The times are in minutes:seconds:milliseconds
> i'm doing ok in printing the right minutes and seconds my problem is with the milliseconds.
>
> Example if i have 00:02:20 and 00:04:40 the average will be 00:03:30 or 00:02:00 and 00:03:00 will be 00:02:30
>
If the final 2 digits are milliseconds, then the second average would
be 00:02:500; if they're centiseconds (hundredths of a second), then
the second average would be 00:02:50.

If the average you give is correct ('00:02:30'), then that suggests
that they are in fact hours:minutes:seconds.

> Can anyone help me out with this please. Here is the code that i have so far:
>
> def lap_average(lap1, lap2):
>
>      t1 = lap1.replace(":",'')
>      t2 = lap2.replace(":",'')
>
>      mins1, secs1, hundreths1 = t1[:2], t1[2:4], t1[4:]
>      mins2, secs2, hundreths2 = t2[:2], t2[2:4], t2[4:]
>
>      total_seconds = int(secs1) + int(secs2) + int(mins1) * 60 + int(mins2) * 60
>
>      millisec = (total_seconds * 1000)
>      millisec = millisec / 2
>
>      micro_x = millisec
>      minutes = micro_x / (60*1000)
>
>      micro_x = micro_x - minutes * (60*1000)
>      seconds = micro_x / 1000
>      micro_x = micro_x - seconds
>
>     print '%02d:%02d:%s' % (minutes, seconds, micro_x)
>
> lap_average('03:40:00', '05:20:00')
> lap_average('03:00:02', '02:00:00')
> lap_average('02:25:50', '06:50:75')
> lap_average('00:02:00', '00:03:00')
> lap_average('00:02:20', '00:04:40')
> lap_average('02:40:40', '03:30:30')
> lap_average('02:60:30', '60:40:40')
>
> Thanks in Advance
>
I don't see the point of these 2 lines of removing the ':'; slice
'lap1' and 'lap2' instead:

     mins1, secs1, hundreths1 = lap1[:2], lap1[3:5], lap1[6:]
     mins2, secs2, hundreths2 = lap2[:2], lap2[3:5], lap2[6:]

Better yet, split on ':':

     mins1, secs1, hundreths1 = lap1.split(':')
     mins2, secs2, hundreths2 = lap2.split(':')

Incidentally, you're talking about milliseconds, but the names say
'hundreths'.

A useful function is 'divmod', which, as its name suggests, performs
both (integer) division and modulo in one step:

     seconds, millisec = divmod(millisec, 1000)
     minutes, seconds = divmod(seconds, 60)




More information about the Python-list mailing list