How to round a time in python?

Good day!

For example I have a number of seconds, 3590
I'm using a timedelta can obtain a string representation, such 00:59:50
And I need to round up to 1 hour

Guys, tell me is there any simple method or library to round a time in Python?
March 12th 20 at 08:00
2 answers
March 12th 20 at 08:02
Solution
Share your number of seconds a number of seconds per hour (3600) - get the number of hours. Round to integer (round method), then multiply by 3600. As a result, you will get the number of seconds in a whole number of hours.
March 12th 20 at 08:04
Solution
>>> def round_time(x):
... hour_in_seconds = 60 * 60
... half_hour_in_seconds = 60 * 30
... if x % hour_in_seconds > half_hour_in_seconds:
... return ((x // hour_in_seconds) + 1) * hour_in_seconds
... else:
... return (x // hour_in_seconds) * hour_in_seconds
... 
>>> 
>>> str(datetime.timedelta(seconds=3590))
'0:59:50'
>>> str(datetime.timedelta(seconds=round_time(3590)))
'1:00:00'

>>> str(datetime.timedelta(seconds=390))
'0:06:30'
>>> str(datetime.timedelta(seconds=round_time(390)))
'0:00:00'

>>> str(datetime.timedelta(seconds=5390))
'1:29:50'
>>> str(datetime.timedelta(seconds=round_time(5390)))
'1:00:00'

>>> str(datetime.timedelta(seconds=7390))
'2:03:10'
>>> str(datetime.timedelta(seconds=round_time(7390)))
'2:00:00'
Thanks for the algorithm! - Keegan.Goldn commented on March 12th 20 at 08:07

Find more questions by tags Python