Skip to content

Latest commit

 

History

History
64 lines (50 loc) · 2.25 KB

File metadata and controls

64 lines (50 loc) · 2.25 KB

Get Absolute Seconds From timedelta Object

The timedelta object provided by datetime is a useful built-in concept for representing a duration of time.

>>> from datetime import timedelta
>>> diff = timedelta(hours=1, minutes=1, seconds=6)
>>> diff.seconds
3666

It is pretty minimal though. There are only a couple things you can inspect about it -- days, seconds (as I did in the snippet above), and microseconds.

And perhaps that is enough to hint at the issue I recently ran into with it -- specifically that you can access both days and seconds.

Let's look at what happens when I have a timedelta with more than a day worth of seconds.

>>> diff = timedelta(seconds=(3600 * 24 + 1))
>>> diff.seconds
1
>>> diff.days
1

I thought seconds was going to produce 86401 instead of 1. The reason is because any amount of duration over a day gets converted into the days value and its the remaining time smaller than a day that is represented by seconds.

In my original implementation of format_time_delta, I was trying to build a relative time string by converting seconds into hours, minutes, and seconds. That approach falls apart as soon as the delta is greater than a day.

def format_time_delta(diff) -> str:
    hours, remainder = divmod(diff.seconds, 3600)
    minutes, remainder = divmod(remainder, 60)
    seconds = remainder

    # ...

Instead, I needed to reach for the total_seconds() function. This gives "the total number of seconds contained in the duration" and is described as equivalent to diff / timedelta(seconds=1).

Here is the updated version of format_time_delta:

def format_time_delta(diff: timedelta) -> str:
    total_seconds = int(diff.total_seconds())

    hours, remainder = divmod(total_seconds, 3600)
    minutes, remainder = divmod(remainder, 60)
    seconds = remainder