How do you convert numbers to seconds in python?

This is how I got it.

def sec2time(sec, n_msec=3):
    ''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
    if hasattr(sec,'__len__'):
        return [sec2time(s) for s in sec]
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    if n_msec > 0:
        pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
    else:
        pattern = r'%02d:%02d:%02d'
    if d == 0:
        return pattern % (h, m, s)
    return ('%d days, ' + pattern) % (d, h, m, s)

Some examples:

$ sec2time(10, 3)
Out: '00:00:10.000'

$ sec2time(1234567.8910, 0)
Out: '14 days, 06:56:07'

$ sec2time(1234567.8910, 4)
Out: '14 days, 06:56:07.8910'

$ sec2time([12, 345678.9], 3)
Out: ['00:00:12.000', '4 days, 00:01:18.900']

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    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 approach is simply a naive approach to get the hours, minutes and seconds by simple mathematical calculations. 

    Python3

    def convert(seconds):

        seconds = seconds % (24 * 3600)

        hour = seconds // 3600

        seconds %= 3600

        minutes = seconds // 60

        seconds %= 60

        return "%d:%02d:%02d" % (hour, minutes, seconds)

    n = 12345

    print(convert(n))

    Time Complexity: O(1)
    Auxiliary Space: O(1)

      Approach #2 : Alternate to the Naive approach By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations. 

    Python3

    def convert(seconds):

        min, sec = divmod(seconds, 60)

        hour, min = divmod(min, 60)

        return '%d:%02d:%02d' % (hour, min, sec)

    n = 12345

    print(convert(n))

    Time Complexity: O(1)
    Auxiliary Space: O(1)

      Approach #3 : Using timedelta (Object of datetime module) 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. 

    Python3

    import datetime

    def convert(n):

        return str(datetime.timedelta(seconds = n))

    n = 12345

    print(convert(n))

    Time Complexity: O(1)
    Auxiliary Space: O(1)

      Approach #4 : Using time.strftime() time.strftime() gives more control over formatting. The format and time.gmtime() is passed as argument. gmtime is used to convert seconds to special tuple format that strftime() requires. 

    Python3

    import time

    def convert(seconds):

        return time.strftime("%H:%M:%S", time.gmtime(n))

    n = 12345

    print(convert(n))

    Time Complexity: O(1)
    Auxiliary Space: O(1)


    How do you convert to seconds in Python?

    Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch. Use the timestamp() method. If your Python version is greater than 3.3 then another way is to use the timestamp() method of a datetime class to convert datetime to seconds.

    How do you convert int to seconds in Python?

    “python datetime convert integer to seconds” Code Answer's.
    >>> def frac(n):.
    ... i = int(n).
    ... f = round((n - int(n)), 4).
    ... return (i, f).
    >>> frac(53.45).
    (53, 0.45) # A tuple..

    How do you convert a number to time in Python?

    “how to convert number to time in python” Code Answer minutes = (time*60) % 60. seconds = (time*3600) % 60.

    How do you convert hours minutes seconds to seconds in Python?

    Use the divmod() Function to Convert Seconds Into Hours, Minutes, and Seconds in Python. The divmod() function can convert seconds into hours, minutes, and seconds. The divmod() accepts two integers as parameters and returns a tuple containing the quotient and remainder of their division.