Skip to content Skip to sidebar Skip to footer

How Can I Display Timedelta In Hours:min:sec?

I am exporting a list of timedeltas to csv and the days really messes up the format. I tried this: while time_list[count] > datetime.timedelta(days = 1): time_list[cou

Solution 1:

By default the str() conversion of a timedelta will always include the days portion. Internally, the value is always normalised as a number of days, seconds and microseconds, there is no point in trying to 'convert' days to hours because no separate hour component is tracked.

If you want to format a timedelta() object differently, you can easily do so manually:

defformat_timedelta(td):
    minutes, seconds = divmod(td.seconds + td.days * 86400, 60)
    hours, minutes = divmod(minutes, 60)
    return'{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

This ignores any microseconds portion, but that is trivially added:

return'{:d}:{:02d}:{:02d}.{:06d}'.format(hours, minutes, seconds, td.microseconds)

Demo:

>>> format_timedelta(timedelta(days=2, hours=10, minutes=20, seconds=3))
'58:20:03'>>> format_timedelta(timedelta(hours=10, minutes=20, seconds=3))
'10:20:03'

Solution 2:

If you are ignoring the days in the count, you can convert the timedelta directly.

deftimedelta_to_time(initial_time: timedelta) -> time:
    hour = initial_time.seconds//3600
    minute = (initial_time.seconds//60) % 60
    second = initial_time.seconds - (hour*3600 + minute*60)

    returnstr(datetime.strptime(
        f"{hour}:{minute}:{second}", "%H:%M:%S"
    ).time())

Example:

timedelta_to_time(timedelta(days=2, hours=10, minutes=20, seconds=3))
>> '10:20:03'
timedelta_to_time(timedelta(hours=10, minutes=20, seconds=3))
>> '10:20:03'

Post a Comment for "How Can I Display Timedelta In Hours:min:sec?"