706

I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.

Is there an easy way to convert the seconds to this format in Python?

Vishal Hule
  • 1,311
  • 1
  • 11
  • 16
Specto
  • 8,271
  • 5
  • 23
  • 20
  • 31
    The inverse of this problem can be found at [How to convert an H:MM:SS time string to seconds in Python?](http://stackoverflow.com/questions/6402812/how-to-convert-an-hmmss-time-string-to-seconds-in-python) – hughes Jun 19 '11 at 14:21

20 Answers20

1180

You can use datetime.timedelta function:

>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
Božo Stojković
  • 2,893
  • 1
  • 27
  • 52
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • 13
    This is the best way, IMHO, as you can then use arithmetic on the timedelta and any datetime objects. – Matthew Schinckel Apr 22 '09 at 03:13
  • 20
    This works for multiple days: `str(datetime.timedelta(seconds=60*60*24+1))` = `'1 day, 0:00:01'` – hyprnick Dec 29 '14 at 15:37
  • 8
    `str(datetime.timedelta(seconds=round(666666.55)))` correctly renders days; supresses the decimal seconds. – CPBL Nov 27 '16 at 19:43
  • 1
    `timedelta` is not overflow safe and cannot correctly perform mathematical operations, e.g. `str(timedelta(hours=8) - timedelta(hours=10))` the result is `'-1 day, 22:00:00'` and the integer based solution is exactly for those situations where you need `'-02:00:00'`. – cprn Sep 21 '17 at 17:02
  • 1
    +1. This answer can be modified very easily. For example, if you want to omit a field when printing, use this: https://stackoverflow.com/questions/7999935/python-datetime-to-string-without-microsecond-component – eric_kernfeld Oct 10 '18 at 15:40
  • 1
    To display 2 digit hour just add zfill(8). `str(datetime.timedelta(seconds=666)).zfill(8)` '00:11:06' – Faiyaz Haider Jul 13 '19 at 00:55
  • 2
    @FaiyazHaider **That's not proper code.** The timedelta string will also include days and would then say `1 day, 1:23:45` and **your code would change that to `01 day, 1:23:45`.** **As for @cprn's "overflow safety" warning, that's not weird at all**, the objects are not meant to be subtractable in that way. _They're a representation of the difference between two timestamps._ **They're not meant for comparing the difference between two differences between four timestamps (which is what you're basically doing).** ;-) Read the docs. – Mitch McMabers Oct 14 '19 at 21:39
  • **Hey, everyone who wants to convert seconds to hours/minutes/seconds:** Look at my reply to the `divmod` answer here. That's a slow method and should be avoided. The fastest way is to do the math yourself as I showed in my reply to that answer. HOWEVER, using `datetime.timedelta` is almost as fast as the fastest manual method and is MUCH easier to use. There are also alternative methods in https://stackoverflow.com/q/21520105/8874388 – Mitch McMabers Oct 14 '19 at 21:42
  • @MitchMcMabers str(datetime.timedelta(seconds=666)).zfill(8) this will always return '00:11:06' not '01 day, 1:23:45'. And show me proof that its not "proper code", and show me the scale in which you measuring properness of a code snippet. – Faiyaz Haider Oct 17 '19 at 16:48
  • 1
    @FaiyazHaider Sure, no problem, I'll show you where your code breaks: `print( str(datetime.timedelta(seconds=(3*24*60*60)+100)).zfill(8) )` result: `3 days, 0:01:40`. I forgot that zfill won't add the zero to the left when the string is that long, but you still see the problem. There is NO zero to the left of the hours! Your technique never works when the duration is 24 hours or higher. Just keep that in mind. If you always deal with small durations less than 24 hours, then your technique is okay. Over 24 hours, it breaks. – Mitch McMabers Oct 17 '19 at 20:24
  • @MitchMcMabers OP clearly asked about "hours:minutes:seconds" and no days, hence why I hardcoded '8'. Just a quick tip to pad the string - if needed, it was not a solution to anything. But I am glad you took the time to debug it. – Faiyaz Haider Oct 20 '19 at 05:56
  • Can anyone add to the answer how then use string formatting to print the result in this model ? " 3 Days, 1 Hour, 5 minutes and 33 seconds". – Marine Galantin Dec 29 '19 at 15:32
  • 1
    `datetime.timedelta` is not very nice to work with in terms of formatting. You can find some recipes here and there but it is not one-liner. – Wojciech Jakubas Oct 14 '20 at 19:06
  • 1
    This is an old thread, but I want to set straight something @cprn said: `timedelta ... cannot correctly perform mathematical operations, e.g. str(timedelta(hours=8) - timedelta(hours=10)) the result is '-1 day, 22:00:00' ...` Let me explain why this comment is wrong. For a negative interval, you go back in time as far as the negative component specifies and then come forward as far as the positive components specify. So `-1 day, 22:00:00` means go back one day and then forward 22 hours, which gives you "two hours ago." This is obviously correct. – chris Jan 09 '21 at 22:06
  • Would it be possible to show hour in `00` instead of single zero(`0`) – alper Nov 28 '21 at 11:09
  • Actually, this is a great shortcut to using the `divmod` method, as seen in the source of [`datatime.py`](https://github.com/python/cpython/blob/main/Lib/datetime.py): ```def __str__(self): mm, ss = divmod(self._seconds, 60); hh, mm = divmod(mm, 60); s = "%d:%02d:%02d" % (hh, mm, ss)``` – Sébastien Wieckowski Nov 13 '22 at 16:39
706

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:

m, s = divmod(seconds, 60)
h, m = divmod(m, 60)

And then use string formatting to convert the result into your desired output:

print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Brandon Rhodes
  • 83,755
  • 16
  • 106
  • 147
  • 3
    If you prefer operators over functions, use the modulo; for example (only minutes/seconds) : `'%d:%02dmn' % (seconds / 60, seconds % 60)` – bufh May 20 '14 at 14:47
  • 22
    And you can extend it to days: `d, h = divmod(h, 24)`. – Mark Ransom Oct 03 '14 at 14:47
  • 21
    @MarkRansom: and then to months `m, d = divmod(m, 31)`. Oooops, no, you can't. Worse, your code will be wrong if leap seconds come into the game. Long story short: use `timedelta` and don't mess with the calendar, it will bite you. –  Jun 02 '15 at 14:08
  • 5
    @Tibo does `timedelta` deal with leap seconds? I suspect not. There are plenty of applications where this simple math is more than sufficient. – Mark Ransom Jun 02 '15 at 15:08
  • 1
    @MarkRansom `str(timedelta(hours=8) - timedelta(hours=10))` the result is '-1 day, 22:00:00' so... idk if it works with leap seconds but it doesn't work with negative numbers. – cprn Sep 25 '17 at 18:05
  • how can I do this to a column in a pandas dataframe? – bernando_vialli Oct 09 '17 at 14:11
  • @Tibo: Unfortunately, you can't, because `time(0, 0) + timedelta(anything)` is a `TypeError`. You can use `datetime` instead of `time` and then convert with the `.time()` method, but if that unexpectedly overflows, it will silently do the Wrong Thing. – Kevin Feb 23 '18 at 00:47
  • At least first part of the comment by @Tibo should be appended to the answer as a note. While I agree that this is a great approach for simple mathematics and works perfectly to calculate duration till days, it will fail beyond that, i.e., at months. Maybe an additional note that this solution should not be confused as a replacement for any function dedicated for manipulating `datetime` objects. – Fr0zenFyr Mar 23 '18 at 11:01
  • Here it is in the form of a small function `def s2hhmmss(s): m, s = divmod(s, 60) h, m = divmod(m, 60) return str(int(h)).zfill(2) + ':' + str(int(m)).zfill(2) + ':' + str(int(s)).zfill(2)` – stallingOne Jul 17 '18 at 12:16
  • 2
    For those discussing datetimes: please note that the original question does not want the hours broken down into any larger units of time, so anything that creates larger time units than hours would then need them manually reduced back to an integral number of hours. – Brandon Rhodes Jul 18 '18 at 13:13
  • 1
    For easier formatting using [format](https://docs.python.org/2/library/string.html#format-examples): `timestamp = '{0:02}:{1:02}:{2:02}'.format(h, m, s)` – Agustín Lado Aug 10 '18 at 19:33
  • **Well sure it may be more "pythonic", but it is NOT faster.** Compare: `python -m timeit -s "import datetime; start_time = time.time()" "now=time.time(); seconds = int(now-start_time); m, s = divmod(seconds, 60); h, m = divmod(m, 60); foo='{:01}:{:02}:{:02}'.format(h, m, s)"` (1250 nanoseconds) vs `python -m timeit -s "import datetime; start_time = time.time()" "now=time.time(); s = int(now-start_time); foo='{:01}:{:02}:{:02}'.format(s//3600, s%3600//60, s%60)"`(1030 nanosconds). So the `divmod` technique is 21.3% slower. BTW look at https://stackoverflow.com/q/21520105/8874388 for methods. – Mitch McMabers Oct 14 '19 at 21:34
  • @cprn please see my comment on the OP. The results for negative numbers is correct. The docs even mention that this might surprise you at first. Please make sure you understand topics before you complain about their behavior. From the docs: ```Note that normalization of negative values may be surprising at first. For example: >>> >>> from datetime import timedelta >>> d = timedelta(microseconds=-1) >>> (d.days, d.seconds, d.microseconds) (-1, 86399, 999999)``` (see https://docs.python.org/3/library/datetime.html#timedelta-objects) – chris Jan 09 '21 at 22:11
  • @s-k-y-e---c-a-p-t-a-i-n Oh, I understand the subject down to the machine code, including the dubious assumption that drove this decision to represent negative domain arithmetic as an expression. Just wanted to point out it won't work for what the OP wanted when it comes to negative numbers. It's yet another reason (next to unknown leap seconds support) to use custom implementation that stores seconds and converts with `divmod` when needed. – cprn Jan 13 '21 at 05:11
  • 2
    @cprn — I understand the OP to be asking strictly about two ways of measuring an interval of time, in which case the number will never be negative. And, most folks I know want 3600.0 seconds to be called “one hour” whether that hour happens to fall across a leap-second boundary or not; the OP would have had to provide more detail for us to know if the question is really about elapsed time versus “how much has the leap-second-corrected clock hand moved?”, either of which, yes, could have been desired. But in the latter case the start clock time would need to be provided too. – Brandon Rhodes Jan 13 '21 at 17:36
  • @cpm, 1) would your custom divmod code somehow handle leap seconds seamlessly? 2) if you want to know if leap seconds are supported by time deltas, why not grab a leap second from the past and test a timedelta against it? 3) I was originally responding to your false claim, and I quote, that timedelta "cannot correctly perform mathematical operations" just because it reports negative answers. your comment is wrong b/c negative answers are per spec and documented; you need to interpret correct results correctly instead of saying they are wrong just because you don't like them. – chris Jan 14 '21 at 08:20
  • Actually, I just realized that leap seconds have nothing to do with anything here. They might be even less relevant than whether @cprn knows machine code. :) The OP says they have seconds, not a specific start and stop time. So now I'm not sure why leap seconds were ever introduced to this topic, as they don't seem to have anything to do with the OP. Maybe it's just "hate on the timedelta" week, idunno. FYI, I noticed this when I thought about my suggestion to build a timedelta over a leap second. After I posted, I thought "wait a second..." (no pun intended). – chris Jan 14 '21 at 08:27
  • Sorry for the spam, but one more comment: I am not opposed to divmod by any means. I just don't know why people are spreading FUMID (fear, uncertainty, misinformation, and doubt) about timedelta. In fact, when I wanted to show elapsed time as part of my prompt, I wrote a python script that uses ... divmod. It's a good solution. I'm just defending timedelta's honor. :-) – chris Jan 14 '21 at 08:34
  • @BrandonRhodes OP is not asking about measuring anything, they're asking about value storage and it isn't specified whether the value might be negative, hence, they might need to consider that when selecting a solution, thus, I mentioned a known caveat. Also, I wasn't the one to bring up the subject of leap seconds but it might be still relevant if the value returned by OP's function is big enough to span over last leap second (2016-12-31). – cprn Jan 14 '21 at 19:38
  • @s-k-y-e---c-a-p-t-a-i-n My custom code would store seconds as whatever the function returned. Numeric data rarely requires storage in specific format - that's a view issue, not a model issue. I'm not the one bringing up leap seconds, see the comment above. All I meant is `timedelta` is okay for presentation, not for storage. You might need to do operations on stored values and `timedelta` doesn't make it easy in some cases (e.g. negative numbers math). – cprn Jan 14 '21 at 19:50
  • @cprn that makes sense. i'm not at a spot where i can easily view the earlier comments but I was literally wondering "how _did_ leap seconds become a thing in this post?" I probably did think it was you - sorry about that. I'll look again later // sky. – chris Jan 15 '21 at 23:12
  • I am having following pylint warning message `Formatting a regular string which could be a f-strin` , how could I resolve it? – alper Nov 13 '21 at 18:16
  • What is `d`? // `ValueError: Unknown format code 'd' for object of type 'float'` – alper Nov 13 '21 at 18:17
98

I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:

from time import strftime
from time import gmtime

strftime("%H:%M:%S", gmtime(666))
'00:11:06'

strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'

gmtime is used to convert seconds to special tuple format that strftime() requires.

Note: Truncates after 23:59:59

JayRizzo
  • 3,234
  • 3
  • 33
  • 49
anatoly techtonik
  • 19,847
  • 9
  • 124
  • 140
  • 20
    Unfortunately this method starts measuring days from 1 so it isn't designed to represent time delta, and so it is an accident waiting to happen. For example with `time.strftime('%d %H:%M:%S', time.gmtime(1))` => '1 day, 0:00:01'. – Rian Rizvi Jan 01 '16 at 21:49
  • 1
    Can not display decimals for seconds=0.0236 (as Božo Stojković's answer do) – Juha M Jan 07 '22 at 14:09
75

Using datetime:

With the ':0>8' format:

from datetime import timedelta

"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'

"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'

"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'

Without the ':0>8' format:

"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'

"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'

"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'

Using time:

from time import gmtime
from time import strftime

# NOTE: The following resets if it goes over 23:59:59!

strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'

strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'

strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'

strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong
JayRizzo
  • 3,234
  • 3
  • 33
  • 49
marcell
  • 1,332
  • 9
  • 10
  • 1
    it fails if the delta is less than a second: `"{:0>8}".format(timedelta(milliseconds=66)) '0:00:00.066000'` – jfs Sep 12 '15 at 12:21
  • 3
    To everyone else: The `without ':0>8':` example is missing a leading 0. `{:0>8}` zero pads to the left 8 zeroes. – TankorSmash Jul 24 '17 at 22:11
  • 2
    In python 3.5.2, I get a TypeError. I'm formatting a `time.time()-start` variable. Any insight? `TypeError: non-empty format string passed to object.__format__` – medley56 Sep 25 '17 at 16:40
  • I tried using `datetime.now()` instead of `time.time()` to generate my timedelta object and I get the same error. – medley56 Sep 25 '17 at 16:45
  • @medley56 When using Python3, you need to use `str()` if you are going use a format such as `0>8`: `"{:0>8}".format(str(datetime.timedelta(seconds=666777)))`. Check [this answer](https://stackoverflow.com/a/538721/4228275) for more info. – Berriel Sep 11 '18 at 21:10
74

This is my quick trick:

from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'

For more info Visit: https://humanfriendly.readthedocs.io/en/latest/api.html#humanfriendly.format_timespan

Pavin Joseph
  • 123
  • 1
  • 6
doories
  • 741
  • 5
  • 2
  • 5
    You have no idea how long I was looking for this very answer. Thank you so much. I wish I could give you more than a +1. – Armster Jun 05 '20 at 19:23
  • 1
    Amazing. Even adjusts perfectly when the seconds are huge (`604800` becomes `1 week`). – aheze Aug 01 '21 at 19:52
  • 1
    @Armster I know it's a little late, but for answers where a simple upvote isn't enough, you can award a [bounty](https://stackoverflow.com/help/bounty) of your own rep. – MattDMo Apr 19 '22 at 20:21
23

The following set worked for me.

def sec_to_hours(seconds):
    a=str(seconds//3600)
    b=str((seconds%3600)//60)
    c=str((seconds%3600)%60)
    d=["{} hours {} mins {} seconds".format(a, b, c)]
    return d


print(sec_to_hours(10000))
# ['2 hours 46 mins 40 seconds']

print(sec_to_hours(60*60*24+105))
# ['24 hours 1 mins 45 seconds']
JayRizzo
  • 3,234
  • 3
  • 33
  • 49
naive decoder
  • 231
  • 2
  • 3
15

A bit off topic answer but maybe useful to someone

def time_format(seconds: int) -> str:
    if seconds is not None:
        seconds = int(seconds)
        d = seconds // (3600 * 24)
        h = seconds // 3600 % 24
        m = seconds % 3600 // 60
        s = seconds % 3600 % 60
        if d > 0:
            return '{:02d}D {:02d}H {:02d}m {:02d}s'.format(d, h, m, s)
        elif h > 0:
            return '{:02d}H {:02d}m {:02d}s'.format(h, m, s)
        elif m > 0:
            return '{:02d}m {:02d}s'.format(m, s)
        elif s > 0:
            return '{:02d}s'.format(s)
    return '-'

Results in:

print(time_format(25*60*60 + 125)) 
>>> 01D 01H 02m 05s
print(time_format(17*60*60 + 35)) 
>>> 17H 00m 35s
print(time_format(3500)) 
>>> 58m 20s
print(time_format(21)) 
>>> 21s
Tomas Trdla
  • 1,142
  • 1
  • 11
  • 24
14

hours (h) calculated by floor division (by //) of seconds by 3600 (60 min/hr * 60 sec/min)

minutes (m) calculated by floor division of remaining seconds (remainder from hour calculation, by %) by 60 (60 sec/min)

similarly, seconds (s) by remainder of hour and minutes calculation.

Rest is just string formatting!

def hms(seconds):
    h = seconds // 3600
    m = seconds % 3600 // 60
    s = seconds % 3600 % 60
    return '{:02d}:{:02d}:{:02d}'.format(h, m, s)

print(hms(7500))  # Should print 02h05m00s
Sam
  • 510
  • 5
  • 10
  • While this code may provide a solution to the OP's question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Feb 10 '20 at 07:32
12

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']
wsdzbm
  • 3,096
  • 3
  • 25
  • 28
11

If you need to get datetime.time value, you can use this trick:

my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()

You cannot add timedelta to time, but can add it to datetime.

UPD: Yet another variation of the same technique:

my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()

Instead of 1 you can use any number greater than 0. Here we use the fact that datetime.fromordinal will always return datetime object with time component being zero.

MarSoft
  • 3,555
  • 1
  • 33
  • 38
4

dateutil.relativedelta is convenient if you need to access hours, minutes and seconds as floats as well. datetime.timedelta does not provide a similar interface.

from dateutil.relativedelta import relativedelta
rt = relativedelta(seconds=5440)
print(rt.seconds)
print('{:02d}:{:02d}:{:02d}'.format(
    int(rt.hours), int(rt.minutes), int(rt.seconds)))

Prints

40.0
01:30:40
teekarna
  • 1,004
  • 1
  • 10
  • 13
  • 1
    I'm getting different output from yours, which makes me think you have a typo. You probably meant to use `seconds=5440` instead of `seconds=5540`. I like your answer, though! – J-L Jun 05 '19 at 23:52
2

Here is a way that I always use: (no matter how inefficient it is)

seconds = 19346
def zeroes (num):
    if num < 10: num = "0" + num
    return num

def return_hms(second, apply_zeroes):
    sec = second % 60
    min_ = second // 60 % 60
    hrs = second // 3600
    if apply_zeroes > 0:
       sec = zeroes(sec)
       min_ = zeroes(min_)
       if apply_zeroes > 1:
           hrs = zeroes(hrs)
    return "{}:{}:{}".format(hrs, min_, sec)

print(return_hms(seconds, 1))

RESULT: 5:22:26

Syntax of return_hms() function

The return_hms() function is used like this:

The first variable (second) is the amount of seconds you want to convert into h:m:s.

The second variable (apply_zeroes) is formatting:

0 or less: Apply no zeroes whatsoever

1: Apply zeroes to minutes and seconds when they're below 10.

2 or more: Apply zeroes to any value (including hours) when they're below 10.

Lucas Urban
  • 627
  • 4
  • 15
1

Here is a simple program that reads the current time and converts it to a time of day in hours, minutes, and seconds

import time as tm #import package time
timenow = tm.ctime() #fetch local time in string format

timeinhrs = timenow[11:19]

t=tm.time()#time.time() gives out time in seconds since epoch.

print("Time in HH:MM:SS format is: ",timeinhrs,"\nTime since epoch is : ",t/(3600*24),"days")

The output is

Time in HH:MM:SS format is:  13:32:45 
Time since epoch is :  18793.335252338384 days
0

You can divide seconds by 60 to get the minutes

import time
seconds = time.time()
minutes = seconds / 60
print(minutes)

When you divide it by 60 again, you will get the hours

alosha002
  • 45
  • 1
0

In my case I wanted to achieve format "HH:MM:SS.fff". I solved it like this:

timestamp = 28.97000002861023
str(datetime.fromtimestamp(timestamp)+timedelta(hours=-1)).split(' ')[1][:12]
'00:00:28.970'
Andre
  • 103
  • 1
  • 10
0

The solutions above will work if you're looking to convert a single value for "seconds since midnight" on a date to a datetime object or a string with HH:MM:SS, but I landed on this page because I wanted to do this on a whole dataframe column in pandas. If anyone else is wondering how to do this for more than a single value at a time, what ended up working for me was:

 mydate='2015-03-01'
 df['datetime'] = datetime.datetime(mydate) + \ 
                  pandas.to_timedelta(df['seconds_since_midnight'], 's')
0

I looked every answers here and still tried my own

def a(t):
  print(f"{int(t/3600)}H {int((t/60)%60) if t/3600>0 else int(t/60)}M {int(t%60)}S")

Results:

>>> a(7500)
2H 5M 0S
>>> a(3666)
1H 1M 6S

Python: 3.8.8

onlyvinish
  • 435
  • 1
  • 5
  • 20
0

Here's a quick one-liner:

(s = Seconds)

':'.join([str(int(s/60/60 % 60)), str(int(s/60 % 60)), str(int(s%60))])

Output:

'12:31:20'
drew wood
  • 195
  • 1
  • 5
0

A custom solution I came up with:

import math

hours = math.floor(seconds / 3600)
seconds -= hours * 3600

minutes = math.floor(seconds / 60)
seconds -= minutes * 60

seconds = math.floor(seconds)

return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
Marcus
  • 75
  • 2
  • 8
-3

division = 3623 // 3600 #to hours
division2 = 600 // 60 #to minutes
print (division) #write hours
print (division2) #write minutes

PS My code is unprofessional