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

python get hours, minutes, seconds
python convert minutes to hours and minutes
how to convert hours into minutes in python
python convert seconds to hours, minutes, seconds milliseconds
adding hours and minutes in python
convert timestamp to seconds python
python convert seconds to datetime
how to convert seconds into hours, minutes and seconds

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

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'

Python program to convert seconds into hours, minutes and seconds , Datetime module provides timedelta object which represents a duration, the difference between two dates or times. datetime. timedelta can be used to represent seconds into hours, minutes and seconds format. Given an integer n (in seconds), convert it into hours, minutes and seconds.. Examples: Input : 12345 Output : 3:25:45 Input : 3600 Output : 1:00:00 Approach #1 : Naive

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

Python: Convert seconds to day, hour, minutes and seconds , Python: Tips of the Day. Executes the provided function once for each list element​. Example: def tips_for_each(itr, fn): for el in itr: fn(el)  There are several ways to convert seconds to days, hours, minutes and seconds. Here we will see the easiest way to do that. Using the datetime module’s timedelta() object, you can convert the seconds in integer or decimal (with microseconds) value to days, hours, minutes and seconds in one line of code. Here is an example.

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)

Python program to convert seconds into hours, minutes and seconds, Python program to convert seconds into hours, minutes and seconds. Python​Server Side Approach 1: The brute-force method. Example. Python program to convert seconds into hours, minutes and seconds Count of a, b & c after n seconds for given reproduction rate Program to convert given number of days in terms of Years, Weeks and Days

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

How to Convert Seconds to Years with Python, How to Convert Seconds to Years with Python. Start with a number of seconds. Divide by 60 to get the number of minutes: minutes = seconds / 60 print(minutes) Output: 24443409.48451446. Divide by 60 to get the number of hours: hours = minutes / 60 print(hours) Output: 407390.158075241. Develop a program that reads the number of days, hours, minutes, and seconds from the user. Calculate and display the total number of seconds represented by that duration. Load your favorite IDEs on the cloud & code on the go with virtual desktops remotely from your preferred mobile devices (iOS/Android/PC) with CloudDesktopOnline.com .

def normalize_seconds(seconds: int) -> tuple:
    (days, remainder) = divmod(seconds, 86400)
    (hours, remainder) = divmod(remainder, 3600)
    (minutes, seconds) = divmod(remainder, 60)

    return namedtuple("_", ("days", "hours", "minutes", "seconds"))(days, hours, minutes, seconds)

Python's program to Convert time unit seconds in days,hours,minutes, Develop a python program that begins by reading a number of seconds from the user. Then your program should display the equivalent  days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60 As for DST, I think the best thing is to convert both datetime objects to seconds. This way the system calculates DST for you.

8.1. datetime — Basic date and time types, For related functionality, see also the time and calendar modules. Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo. class datetime.timedelta(days=0, seconds=0, microseconds=0, if and only if, after converting it to minutes and subtracting utcoffset() (or 0 if that's None), the result is non-zero. Last update on February 26 2020 08:09:18 (UTC/GMT +8 hours) Python Basic: Exercise-65 with Solution Write a Python program to convert seconds to day, hour, minutes and seconds.

How to Convert seconds to day, hour, minutes and seconds in Python, How to Convert seconds to day, hour, minutes and seconds in Python. T3SO Tutorials Duration: 4:43 Posted: Apr 17, 2019 Converting seconds into days, hours, minutes and seconds in C++ C++ Server Side Programming Programming In this tutorial, we will be discussing a program to convert seconds into days, hours, minutes and seconds.

Seconds -> Days, Hours, Minutes, and Seconds, python datetime. This is just a simple function to convert seconds to days, hours, minutes and seconds for a larger app I'm going to be building. Using python programming to convert seconds into days,hours, and minutes. Using python programming to convert seconds into days,hours, and minutes. Using floor division and modulo. https

Comments
  • Hint: docs.python.org/library/functions.html#divmod lets you do something like this: divmod(3660,3600) # (1, 60) and divmod(60,60) # (1,0). Also, what exactly are you asking?
  • Write out how you would do it on paper, then turn it into code.
  • Based upon your description, your "if" statements should be '>=', not '<='.
  • Possible duplicate of Python Time Seconds to h:m:s
  • On my Python 2.6.6 system, I had to use result.append("%s %s" % (value, name))
  • I believe there is maximum on seconds. So this is not the suggested way. See the documentation: seconds Between 0 and 86399 inclusive docs.python.org/library/datetime.html
  • There are 86400 seconds in a day, so that's why you can only have 0-86399 seconds. In other words, timedelta(seconds=86400) would resolve to days=1, seconds=0. Therefore, 86399 is not the maximum input value for seconds.
  • Seems I misunderstood the documentation, if its the way you say. So what you mean is, if I use the following timedelta: timedelta(seconds=86450) it will automatically resolve to timedelta(days=1, seconds=50)? Is that correct? Thanks for your comment.
  • If the duration are so long that it changes the month, then this proposal won't work. Try 5184000 (60*24*3600) seconds.
  • using 3.0 style format strings, you can use: t = timedelta(seconds=long(valu)); print("Time to Keep: {}m-{}d {} (h:mm:ss)".format(t.days/30, t.days%30, timedelta(seconds=t.seconds)))
  • I get a TypeError, to fix that: sec = timedelta(seconds=(int(input('Enter the number of seconds: '))))
  • It is not good to just post code as an answer. You should also include some explanation, even if you think it may be self-evident.
  • Doesn't quite fulfill the requirements.