Python second to hh mm ss

If you need to do this a lot, you can precalculate all possible strings for number of seconds in a day:

try:
    from itertools import product
except ImportError:
    def product(*seqs):
        if len(seqs) == 1:
            for p in seqs[0]:
                yield p,
        else:
            for s in seqs[0]:
                for p in product(*seqs[1:]):
                    yield (s,) + p

hhmmss = []
for (h, m, s) in product(range(24), range(60), range(60)):
    hhmmss.append("%02d:%02d:%02d" % (h, m, s))

Now conversion of seconds to format string is a fast indexed lookup:

print hhmmss[12345]

prints

'03:25:45'

EDIT:

Updated to 2020, removing Py2 compatibility ugliness, and f-strings!

import sys
from itertools import product


hhmmss = [f"{h:02d}:{m:02d}:{s:02d}"
             for h, m, s in product(range(24), range(60), range(60))]

# we can still just index into the list, but define as a function
# for common API with code below
seconds_to_str = hhmmss.__getitem__

print(seconds_to_str(12345))

How much memory does this take? sys.getsizeof of a list won't do, since it will just give us the size of the list and its str refs, but not include the memory of the strs themselves:

# how big is a list of 24*60*60 8-character strs?
list_size = sys.getsizeof(hhmmss) + sum(sys.getsizeof(s) for s in hhmmss)
print("{:,}".format(list_size))

prints:

5,657,616

What if we just had one big str? Every value is exactly 8 characters long, so we can slice into this str and get the correct str for second X of the day:

hhmmss_str = ''.join([f"{h:02d}:{m:02d}:{s:02d}"
                      for h, m, s in product(range(24),
                                             range(60),
                                             range(60))])
def seconds_to_str(n):
    loc = n * 8
    return hhmmss_str[loc: loc+8]

print(seconds_to_str(12345))

Did that save any space?

# how big is a str of 24*60*60*8 characters?
str_size = sys.getsizeof(hhmmss_str)
print("{:,}".format(str_size))

prints:

691,249

Reduced to about this much:

print(str_size / list_size)

prints:

0.12218026108523448

On the performance side, this looks like a classic memory vs. CPU tradeoff:

import timeit

print("\nindex into pre-calculated list")
print(timeit.timeit("hhmmss[6]", '''from itertools import product; hhmmss = [f"{h:02d}:{m:02d}:{s:02d}"
                     for h, m, s in product(range(24),
                                             range(60),
                                             range(60))]'''))
print("\nget slice from pre-calculated str")
print(timeit.timeit("hhmmss_str[6*8:7*8]", '''from itertools import product; hhmmss_str=''.join([f"{h:02d}:{m:02d}:{s:02d}"
                     for h, m, s in product(range(24),
                                             range(60),
                                             range(60))])'''))

print("\nuse datetime.timedelta from stdlib")
print(timeit.timeit("timedelta(seconds=6)", "from datetime import timedelta"))
print("\ninline compute of h, m, s using divmod")
print(timeit.timeit("n=6;m,s=divmod(n,60);h,m=divmod(m,60);f'{h:02d}:{m:02d}:{s:02d}'"))

On my machine I get:

index into pre-calculated list
0.0434853

get slice from pre-calculated str
0.1085147

use datetime.timedelta from stdlib
0.7625738

inline compute of h, m, s using divmod
2.0477764

While Programming or writing script, we come across the situation where we need to convert the given seconds into readable hours:minutes: seconds format or vice versa.

This Python tutorial will teach you how to convert a given integer seconds value to hours, minutes, and seconds. And by the end of this tutorial, you will be able to write Python programs and logic for

  1. Conversion of seconds into hours, minutes, and seconds
  2. Conversion of Hours, minutes, and seconds into seconds.

So let’s Get started.

To handle time and date data in Python, we have the inbuilt datetime module. The datetime module contains various subclasses and methods to manipulate, represent and edit time in Python. In the datetime module, we also the timedelta class that can convert given integer seconds to readable hh:mm:ss format. To use timedelta in Python, follow the following steps

Step 1 Import the timedelta class from the datetime module

The datetime is an inbuilt Python module, to import it in our Python script, we can use the from and import keywords.

from datetime import  timedelta

Step 2 convert the given seconds into hh:mm:ss using timedelta

The timedelta() class can accept the given seconds as keyword argument seconds , and return a datetime.timedelta object representing the given seconds into hh:mm:ss format.

#seconds
given_seconds = 6000

print("Time in Seconds is: ",given_seconds)

#convert the seconds into hh:mm:ss
td = timedelta(seconds = given_seconds)

print(f"The {given_seconds} are equal to hh:mm:ss=", td)

Output

Time in Seconds is:  6000
The 6000 are equal to hh:mm:ss= 1:40:00

Example 2

For the given seconds argument, the timedelta() class returns timedelta() object in hh:mm:ss format, which is not that readable.  To display the conversion of seconds into hours, minutes, and seconds, we first have to convert the return result into a string using str() function, then display it correctly.

from datetime import timedelta

#seconds
given_seconds1 = 5463

print("Time in Seconds is: ",given_seconds1)

#convert the seconds into hh:mm:ss string
td1 = str(timedelta(seconds = given_seconds1))

#get the hh, mm and ss from the string
hh2, mm1, ss1 = td1.split(":") 

print(f"The {given_seconds1} seconds in hh:mm:ss is {hh2} Hours {mm1} Minutes {ss1} Seconds \n" )

#seconds
given_seconds2 = 78374

print("Time in Seconds is: ",given_seconds2)

#convert the seconds into hh:mm:ss string
td1 = str(timedelta(seconds = given_seconds2))

#get the hh, mm and ss from the string
hh2, mm1, ss1 = td1.split(":") 

print(f"The {given_seconds2} seconds in hh:mm:ss is {hh2} Hours {mm1} Minutes {ss1} Seconds \n" )

Output

Time in Seconds is:  5463
The 5463 seconds in hh:mm:ss is 1 Hours 31 Minutes 03 Seconds 

Time in Seconds is:  78374
The 78374 seconds in hh:mm:ss is 21 Hours 46 Minutes 14 Seconds

How to convert seconds to Hours, Minutes, and Seconds in Python with the time module?

Python also has a time module that is specifically used to deal with time data in Python.  The time module supports a gmtime() method that is used to convert given seconds to a full date and time from the epoch that is January 1, 1970, 00:00:00 (UTC). We can take the help of this method and convert the given seconds into hours, minutes and seconds.

Example

import time

#seconds
given_seconds = 86399

print("Time in Seconds is: ",given_seconds)

#get the time
td = time.gmtime(given_seconds)

#convert the gmtime object to string
td = time.strftime("%H Hours %M Minutes %S seconds", td)

print(f"The {given_seconds} seconds in hh:mm:ss {td}" )

Output

Time in Seconds is:  86399
The 86399 seconds in hh:mm:ss 23 Hours 59 Minutes 59 seconds
Note: The downside of time.gmtime() method, it can only convert given seconds upto 23 hours, 59 minutes, and 59 seconds. If the seconds are more than  86399 it will show some inappropriate results.

How to convert seconds to Hours, Minutes, and Seconds in Python with Naive logic?

You are giving a Python interview. The interviewer asks you to write a Python script that can convert given seconds into hours, minutes, and seconds without using any inbuilt module or function. In such a situation, you need to write a logic that can convert the seconds to the required output. This hardcoded logic technique is also known as naive logic or naive method.

Seconds to the hour, minutes, and second conversion Logic

seconds = give_seconds % (24*3600)  #here 24 represents the hours for 1 day only

hours =  seconds  / 3600

seconds = seconds % 3600

minutes = seconds / 60 

seconds = seconds % 60

Example

#seconds
given_seconds = 86400

print("Time in Seconds is: ",given_seconds)

#8760 represent the hours in a year
seconds = given_seconds % (8760*3600)

hours = seconds // 3600

seconds = seconds % 3600

minutes = seconds //60

seconds = seconds % 60

print(f"The {given_seconds} seconds in hh:mm:ss is {hours} Hours {minutes} Minutes {seconds} Seconds" )

Output

Time in Seconds is:  86400
The 86400 seconds in hh:mm:ss is 24 Hours 0 Minutes 0 Seconds

How to Convert Hours, Minutes, and Seconds to seconds in Python

The conversion of hours, minutes, and seconds into total seconds is effortless, all we do is convert every individual entity to seconds and sum them. For example, we can convert the hour into seconds by multiplying the hour value by 3600 because there are 3600 seconds in an hour. Similarly, we can multiply the given minutes by 60 seconds by 1 and sum them together.

Formula to convert hours, minutes and seconds to seconds

(hours * 3600) + (minutes * 60) + (seconds*1)

Example

def total_seconds(hh_mm_ss):
    #split the string into hour, minutes and seconds
    hour , minutes , seconds = hh_mm_ss.split(":")

    return int(hour)*3600 + int(minutes)*60 + int(seconds)*1

hh_mm_ss_1 = "01:00:00"
hh_mm_ss_2 = "00:35:12"
hh_mm_ss_3 = "00:55:15"

print("Time in hh:mm:ss", hh_mm_ss_1)
print("Time in Seconds: ", total_seconds(hh_mm_ss_1), end ="\n\n")

print("Time in hh:mm:ss", hh_mm_ss_2)
print("Time in Seconds: ", total_seconds(hh_mm_ss_2), end ="\n\n")

print("Time in hh:mm:ss", hh_mm_ss_3)
print("Time in Seconds: ", total_seconds(hh_mm_ss_3), end ="\n\n")

Output

Time in hh:mm:ss 01:00:00
Time in Seconds:  3600

Time in hh:mm:ss 00:35:12
Time in Seconds:  2112

Time in hh:mm:ss 00:55:15
Time in Seconds:  3315

Conclusion

In this Python tutorial you learned how to convert the given seconds into hours, minutes, and seconds. This tutorial discussed three different techniques you can use to perform the task, including using inbuilt modules and using a naive approach.

In this tutorial, we have also discussed how we can convert the given hours, minutes, and seconds back to total seconds, which is very easy compared to converting the seconds to hh:mm:ss.

If you have any suggestions regarding this article or any queries, please comment in the comments sections. We will be appreciated your feedback.

People are also reading:

  • Polymorphism in Python
  • Python inheritance
  • Python Programs to Print Pattern
  • Basic Python Exercise
  • Create files in Python
  • Find the length of a List in Python
  • Slice Lists/Arrays and Tuples in Python
  • Shuffle list in Python using random.shuffle() function
  • Python Compile Regex Pattern using re.compile()
  • Python PostgreSQL Tutorial Using Psycopg2

How do you convert seconds to HH mm SS format in Python?

Use the timedelta() constructor and pass the seconds value to it using the seconds argument. The timedelta constructor creates the timedelta object, representing time in days, hours, minutes, and seconds ( days, hh:mm:ss.ms ) format. For example, datetime.

How do you convert seconds to HH mm SS?

To convert seconds to HH:MM:SS : Multiply the seconds by 1000 to get milliseconds.

How do I convert seconds to hours 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.

How do you get HH mm SS in Python?

strftime('%H:%M:%S', time.