I have a task in which i need to calculate the runtime of a marathon. I'm given this as a start point
start_hour = 3
start_minute = 48
length = 172
Basically the start is at 3:48 and it continues for 172 minutes. My task is to find when the marathon ends.The endtime should look like this format 3:48 with minutes and hour converted to string and put together with ":". I have spent like 1 and a half hour and i still can't manage to solve it. This is what i have come out with:
endhour = start_hour + (length // 60)
endminute = start_minute + (length % 60)
end_minutee = endminute % 60
format(endhour)
endhourAsStr = str(endhour)
end_minuteeAsStr = str(end_minutee)
print(endhourAsStr + ":" + end_minuteeAsStr)
But when i print the final hour is shorter then it should be with 1 hour. I'm guessing that i need to do something with the > or < but i really can't figure it out.I guess that i only need that final push. offtopic: I'm very new to proggraming i don't have experience whatsoever.
You can use some datetime
trickery to get a guaranteed correct result:
start_hour = 3
start_minute = 48
length = 172
start = datetime.datetime(100, 1, 1, start_hour, start_minute, 0)
end = start + datetime.timedelta(minutes=length)
result = str(end.time())
If you want to get rid of the :00
seconds at the end, simply modify the last line:
result = end.strftime('%H:%M')
I prefer this approach because it accounts for edge cases like starting one day near midnight and ending in the next day.
I would suggest
endhour = start_hour + (length // 60)
endminute = start_minute + (length % 60)
endhour += endminute // 60
endminute = endminute % 60
endhour = endhour % 24
print('{}:{}'.format(endhour, endminute))
After initializing the end hour and minute as you did, you extract again the minutes and hours from the end minutes.
Finally, you adjust the hours to be between 0 and 23.
How about keeping everything in minutes and then working out the output as intended later? Keeping it simple to understand and read :)
start_time = start_hour*60 + start_minute
end_time = start_time + length
end_hour, end_minute = end_time // 60, end_time % 60
print('{}:{}'.format(end_hour, end_minute))
# 6:40
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With