-3

I have a float 12634.0 as a duration result. I want to convert it to this format: Months:Days:Hours:Minutes:Seconds (00:00:03:30:34)

How can I achieve that? Thanks

2 Answers2

3

You could try

import datetime
print (str(datetime.timedelta(seconds=12634))
Hannu
  • 11,685
  • 4
  • 35
  • 51
  • This does not print months and days in your desired format. If that is important, you need to follow the brute force method in @bierschi:s answer. This is the quick and dirty solution with only one line of code it it is suitable. – Hannu Jan 02 '18 at 16:05
  • This does not print months and days indeed, but thanks anyway – Xenophon Psichis Jan 02 '18 at 16:09
  • No, it does not. It is just a simple thing that may or may not be helpful. If you need the full conversion, there are no library functions to do that. You need to do a brute force conversion where you split seconds to larger units manually and then combine and display in desired format. This may be helpful in writing such a function: https://stackoverflow.com/questions/538666/python-format-timedelta-to-string – Hannu Jan 02 '18 at 16:25
0

Another solution, if you want additional information like weeks:

import datetime

def time_in_sec(time_sec):

    delta = datetime.timedelta(seconds=time_sec)
    delta_str = str(delta)[-8:]
    hours, minutes, seconds = [int(val) for val in delta_str.split(":", 3)]
    weeks = delta.days // 7
    days = delta.days % 7
    return "{}:{}:{}:{}:{}".format(weeks, days, hours, minutes, seconds)


def time_in_sec2(seconds):

    WEEK = 60 * 60 * 24 * 7
    DAY = 60 * 60 * 24
    HOUR = 60 * 60
    MINUTE = 60

    weeks = seconds // WEEK
    seconds = seconds % WEEK
    days = seconds // DAY
    seconds = seconds % DAY
    hours = seconds // HOUR
    seconds = seconds % HOUR
    minutes = seconds // MINUTE
    seconds = seconds % MINUTE
    return "{}:{}:{}:{}:{}".format(weeks, days, hours, minutes, seconds)


def main():
    print(time_in_sec(12634.0))
    print(time_in_sec2(12634.0))

The result is:

0:0:3:30:34
0.0:0.0:3.0:30.0:34.0

If you dont want information like weeks, so you can simply remove it

You can take solution 2 (time_in_sec2) if you dont want dependencies like

import datetime

bierschi
  • 322
  • 3
  • 11