Explain Codes LogoExplain Codes Logo

Format timedelta to string

python
timedelta
datetime-formatting
humanize
Anton ShumikhinbyAnton Shumikhin·Oct 18, 2024
TLDR

To translate a timedelta entity into a string, either leverage str() for a quick conversion or architect your own format with str.format(). Using delta.total_seconds() enables access to specific time units:

from datetime import timedelta delta = timedelta(days=2, hours=3, minutes=4, seconds=5) # Default string representation, easy peasy lemon squeezy: print(str(delta)) # "2 days, 3:04:05" # Custom formatting (e.g., hours:minutes), a bit like a watchmaker tinkering about: hours, remainder = divmod(delta.total_seconds(), 3600) minutes = remainder // 60 print(f'{int(hours):02}:{int(minutes):02}') # "51:04"

str(delta) serves up the default dish of the day. For custom courses, mince and marinate total_seconds() as desired.

Advanced timedelta formatting

When it comes to seasoning timedelta objects in a way that's palatable to a Django web app or Google AppEngine, the presentation of time is a dish best served explicitly.

Chopping up the hours and minutes:

str_hours, str_minutes = str(delta).split(':', 2)[:2] formatted_string = f'{str_hours}h {str_minutes}m' print(formatted_string) # "51h 04m", we're done cooking here!

Django's contrib.humanize to the rescue:

from django.utils.duration import duration_string print(duration_string(delta)) # "2 days, 3 hours", you're a wizard, Django!

Homo Sapien readable format with humanize:

import humanize print(humanize.naturaldelta(delta)) # "2 days, 3 hours", like asking Siri!

Double-check your kitchen timer to ensure accurate conversions. Remember to account for delicious decimal values in the recipe.

Meet the use cases

The world of timedelta formatting is varied, like an eclectic buffet. Let's sink our teeth into some common dishes:

A) Countdown to perfection

Ensure your minutes and seconds serve up double-digits for maximum presentation impact:

print(f'{int(hours):02}:{int(minutes):02}') # "51:04"

B) Explain like I'm five

For user interfaces that hunger for readable information:

print(humanize.naturaldelta(delta)) # "2 days, 3 hours"

C) In time with timezone

Mind your location cues when localizing time presentation. Timezone variances aren't just for jet lag!

D) Not-so-rounded seconds

Got timedeltas with more than just whole seconds? Aim a cheeky wink at the milliseconds:

seconds = remainder % 60 milliseconds = delta.microseconds // 1000 print(f'{int(minutes):02}:{int(seconds):02}.{milliseconds:03}') # "04:05.000", centiseconds need love too!

Let's beat the common pitfalls

Like any recipe, there's room for error. Let's prep for common mistimed steps.

- Overcooked calculations

Errors often pop in from miscalculations when converting units. Bad math can make your beautiful souffle fall flat!

- Mixed-up timezones

If you don't add a pinch of timezone awareness to a timedelta, it can leave a sour taste.

- Overstepping timedelta boundaries

timedelta isn't your magic bullet for periods beyond days. You need a different sauce for your years and months!