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