# Python function to convert seconds into minutes, hours, and days

### Question

Question: Write a program that asks the user to enter a number of seconds, and works as follows:

• There are 60 seconds in a minute. If the number of seconds entered by the user is greater than or equal to 60, the program should display the number of minutes in that many seconds.

• There are 3600 seconds in an hour. If the number of seconds entered by the user is greater than or equal to 3600, the program should display the number of hours in that many seconds.

• There are 86400 seconds in a day. If the number of seconds entered by the user is greater than or equal to 86400, the program should display the number of days in that many seconds.

What I have so far:

def time():
sec = int( input ('Enter the number of seconds:'.strip())
if sec <= 60:
minutes = sec // 60
print('The number of minutes is {0:.2f}'.format(minutes))
if sec (<= 3600):
hours = sec // 3600
print('The number of minutes is {0:.2f}'.format(hours))
if sec <= 86400:
days = sec // 86400
print('The number of minutes is {0:.2f}'.format(days))
return
1
32
10/29/2010 2:57:18 AM

This tidbit is useful for displaying elapsed time to varying degrees of granularity.

I personally think that questions of efficiency are practically meaningless here, so long as something grossly inefficient isn't being done. Premature optimization is the root of quite a bit of evil. This is fast enough that it'll never be your choke point.

intervals = (
('weeks', 604800),  # 60 * 60 * 24 * 7
('days', 86400),    # 60 * 60 * 24
('hours', 3600),    # 60 * 60
('minutes', 60),
('seconds', 1),
)

def display_time(seconds, granularity=2):
result = []

for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
result.append("{} {}".format(value, name))
return ', '.join(result[:granularity])

..and this provides decent output:

In [52]: display_time(1934815)
Out[52]: '3 weeks, 1 day'

In [53]: display_time(1934815, 4)
Out[53]: '3 weeks, 1 day, 9 hours, 26 minutes'
45
5/3/2016 4:01:06 PM