Aizayousaf
Aizayousaf

Reputation: 49

How to get minutes and seconds(mm:ss) from a timedelta object in python

I'm writing a code in which I have added Time duration for each utterance(given as list of durations for each utterance) and the result is a timedelta showing sum of duration of all utterances. I need the result in only minutes and seconds**(mm:ss)** format.

Code

def add_time(timeList):
   sums = datetime.timedelta()
   for i in timeList:
      x = datetime.datetime.strptime(i, '%M:%S.%f')
      d=datetime.timedelta(minutes=x.minute,seconds=x.second,microseconds=x.microsecond)
    sums += d
    print(str(sums))
    return sums
add_time(['00:04.0', '00:15.2', '1:10.4'])

Output

The output is like this:

 0:01:29.600000
 Out[148]: datetime.timedelta(0, 89, 600000)

How can I get minutes and seconds from a timedelta object?

Upvotes: 0

Views: 449

Answers (1)

Uri Granta
Uri Granta

Reputation: 1904

something like this should work:

 "{}:{:02d}".format(*divmod(sums.seconds, 60))

Upvotes: 3

Related Questions