Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating hours and minutes in python

Tags:

python

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.

like image 770
ilio Avatar asked Aug 14 '17 11:08

ilio


3 Answers

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.

like image 74
stelioslogothetis Avatar answered Oct 21 '22 00:10

stelioslogothetis


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.

like image 3
Uriel Avatar answered Oct 21 '22 01:10

Uriel


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
like image 1
shad0w_wa1k3r Avatar answered Oct 21 '22 02:10

shad0w_wa1k3r