Convert a timedelta to days, hours, and minutes
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:
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:
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.
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:
Was this article helpful?