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
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