I am writing a program that tracks running performance using Python.
It calculates the runner's pace given the calculated elapsed_time
and the distance
.
The issue I am facing is in the calculation of the difference between the runner's pace and their predicted pace. This difference can be positive or negative, as you can run faster than predicted or slower than predicted. However, in the example code (below) I get the result diff = 23:59:54
. The result I want is diff = -00:00:06
.
Any ideas on what to do? I had a vague idea that datetime.timedelta
might help. But as far as I can see there is no way to format a timedelta
as a string...?
import timedef time_to_secs(t): hour, minute, seconds = t.split(':') adjustedtime = (int(hour)*3600) + (int(minute)*60) + int(seconds) return adjustedtimedef time_to_string(t): ty_res = time.gmtime(t) result = time.strftime("%H:%M:%S",ty_res) return resultpredicted_pace = '00:04:10'distance = 10.0elapsed_time = '00:42:42'pace = time_to_string((time_to_secs(elapsed_time)/distance))diff = time_to_string(time_to_secs(predicted_pace) - time_to_secs(pace))print(f'Your total time over {distance} km was {elapsed_time} with a pace of {pace} per km')print(f'Your predicted pace was {predicted_pace} per km')print(f'Difference between predicted and actual pace was {diff}')