Explain Codes LogoExplain Codes Logo

Convert a timedelta to days, hours, and minutes

python
time-precision
datetime
timedelta
Anton ShumikhinbyAnton Shumikhin·Feb 2, 2025
TLDR

To convert a timedelta to days, hours, and minutes, use divmod() for an efficient twist to the computation. Here is a function that encapsulates this logic:

from datetime import timedelta def convert_timedelta(td): # They see me divmodin', they hatin' mins, secs = divmod(td.seconds, 60) hrs, mins = divmod(mins, 60) return f"{td.days}d {hrs}h {mins}m {secs}s" # Let's see the magic happen! td = timedelta(days=2, hours=3, minutes=40) print(convert_timedelta(td)) # The output will be: "2d 3h 40m 0s"

With this piece of code, days are obtained directly as td.days, while hours, minutes, and seconds are extracted finely using divmod() on td.seconds.

Dealing with daylight saving time

While timedelta gives you the broad strokes for converting time durations, it doesn't tell you about the peculiarities of the real world - like Daylight Saving Time (DST). Your code needs to be aware of such time adjustments to stay accurate under all circumstances.

Here's an example of how to handle DST:

import time from datetime import datetime, timedelta def adjust_for_dst(dt): # Tick-tock on the clock, but the party don't stop no! if time.localtime().tm_isdst and time.gmtime().tm_isdst: dt += timedelta(hours=1) return dt now = datetime.now() td = timedelta(days=1) future_time = adjust_for_dst(now + td)

Special care with timestamps

If you're dealing with timestamps and need to convert datetime objects to epoch time, Python's time.mktime can be your best friend. Efficient and simple.

import time from datetime import datetime def datetime_to_epoch(dt): return time.mktime(dt.timetuple()) # Let's rock it to the epoch! now_epoch = datetime_to_epoch(datetime.now())

Time precision: dealing with seconds and microseconds

If you need your time reporting to be as precise as a Swiss watch, then you shouldn't ignore seconds and microseconds. Here's the timedelta conversion enriched to reflect this:

def convert_pretty(td): mins, secs = divmod(td.seconds, 60) hrs, mins = divmod(mins, 60) microsecs = td.microseconds # Time is precious, waste it wisely! result = f"{td.days} days {hrs} hours {mins} minutes {secs}.{microsecs} seconds" return result