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

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

Solution 1:

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'

Solution 2:

This will convert n seconds into d days, h hours, m minutes, and s seconds.

from datetime import datetime, timedelta

def GetTime():
    sec = timedelta(seconds=int(input('Enter the number of seconds: ')))
    d = datetime(1,1,1) + sec

    print("DAYS:HOURS:MIN:SEC")
    print("%d:%d:%d:%d" % (d.day-1, d.hour, d.minute, d.second))

Solution 3:

I'm not entirely sure if you want it, but I had a similar task and needed to remove a field if it is zero. For example, 86401 seconds would show "1 days, 1 seconds" instead of "1 days, 0 hours, 0 minutes, 1 seconds". THe following code does that.

def secondsToText(secs):
    days = secs//86400
    hours = (secs - days*86400)//3600
    minutes = (secs - days*86400 - hours*3600)//60
    seconds = secs - days*86400 - hours*3600 - minutes*60
    result = ("{} days, ".format(days) if days else "") + \
    ("{} hours, ".format(hours) if hours else "") + \
    ("{} minutes, ".format(minutes) if minutes else "") + \
    ("{} seconds, ".format(seconds) if seconds else "")
    return result

EDIT: a slightly better version that handles pluralization of words.

def secondsToText(secs):
    days = secs//86400
    hours = (secs - days*86400)//3600
    minutes = (secs - days*86400 - hours*3600)//60
    seconds = secs - days*86400 - hours*3600 - minutes*60
    result = ("{0} day{1}, ".format(days, "s" if days!=1 else "") if days else "") + \
    ("{0} hour{1}, ".format(hours, "s" if hours!=1 else "") if hours else "") + \
    ("{0} minute{1}, ".format(minutes, "s" if minutes!=1 else "") if minutes else "") + \
    ("{0} second{1}, ".format(seconds, "s" if seconds!=1 else "") if seconds else "")
    return result

EDIT2: created a gist that does that in several languages

Solution 4:

To convert seconds (as string) into datetime, this could also help. You get number of days and seconds. Seconds can be further converted into minutes and hours.

from datetime import datetime, timedelta
sec = timedelta(seconds=(int(input('Enter the number of seconds: '))))
time = str(sec)