Python Convert Seconds to Days, Hours, Minutes and Seconds – Python Tutorial

By | May 30, 2023

Somtimes we only get seconds and have to convert it to days, hours, minutes and seconds. In this tutorial, we will introduce you how to do.

For example, we have a time with 667.454 seconds, we will convert it to 00:11:07.454

How to convert seconds to days, hours, minutes and seconds?

We can create a function to convert. Here is an example:

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:
text = pattern % (h, m, s)
else:
text = ('%d days, ' + pattern) % (d, h, m, s)
return text

x = sec2time(667.454)

Run this code, we will see: 00:11:07.454

We can convert more seconds.

For example:

x = sec2time(667)
print(x)

x = sec2time(6670.45)
print(x)

x = sec2time(6267.2)
print(x)

x = sec2time(6226754)
print(x)

Run this code, we will see:

00:11:07.000
01:51:10.450
01:44:27.200
72 days, 01:39:14.000

Moreover, in some srt (SubRip Subtitle File) file, the time format is:

00:00:08,034 –> 00:00:11,343

We also can convert seconds with this kind of format.

For example:

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:
text = pattern % (h, m, s)
else:
text = ('%d days, ' + pattern) % (d, h, m, s)
text = text.replace(".",",")
return text

x = sec2time(667.55)
print(x)

Run this code, we will see:

00:11:07,550