Python
timedelta
string formatting
datetime
coding tutorial

Format timedelta to string

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Python's timedelta is great for representing durations, but it does not automatically format itself the way many applications need. Sometimes you want HH:MM:SS, sometimes you want days plus time, and sometimes you need to handle negative durations cleanly. The right solution is usually a small helper function that makes the formatting rules explicit.

A Basic HH:MM:SS Formatter

For durations that you want to display as hours, minutes, and seconds, convert total seconds and format the parts manually.

python
1from datetime import timedelta
2
3def format_td(td: timedelta) -> str:
4    total = int(td.total_seconds())
5    hours, rem = divmod(total, 3600)
6    minutes, seconds = divmod(rem, 60)
7    return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
8
9print(format_td(timedelta(hours=2, minutes=5, seconds=9)))  # 02:05:09
10print(format_td(timedelta(seconds=65)))                     # 00:01:05

This is the simplest reliable pattern when you control the output format.

Handling Durations Longer Than One Day

One thing that surprises people is that timedelta internally stores days separately. If you format only the hour remainder, you can accidentally hide extra days.

If you want total hours, the first function is fine. If you want explicit day formatting, write it that way:

python
1from datetime import timedelta
2
3def format_td_with_days(td: timedelta) -> str:
4    total = int(td.total_seconds())
5    days, rem = divmod(total, 86400)
6    hours, rem = divmod(rem, 3600)
7    minutes, seconds = divmod(rem, 60)
8    return f"{days}d {hours:02d}:{minutes:02d}:{seconds:02d}"
9
10print(format_td_with_days(timedelta(days=1, seconds=61)))  # 1d 00:01:01

Choose one representation and keep it consistent across the application.

Handling Negative Timedeltas

Negative durations need special care because the default string representation of timedelta can be unintuitive.

python
1from datetime import timedelta
2
3def format_td_signed(td: timedelta) -> str:
4    total = int(td.total_seconds())
5    sign = "-" if total < 0 else ""
6    total = abs(total)
7
8    hours, rem = divmod(total, 3600)
9    minutes, seconds = divmod(rem, 60)
10    return f"{sign}{hours:02d}:{minutes:02d}:{seconds:02d}"
11
12print(format_td_signed(timedelta(seconds=-75)))  # -00:01:15

Without this explicit handling, negative durations often come out in forms that are technically valid but awkward for users.

Why Not Just Use str(td)

str(timedelta(...)) is fine for quick debugging, but it is not a strong user-facing format because:

  • negative values can look surprising
  • formatting is not always aligned with your product requirements
  • you may want fixed-width output or explicit day labels

In other words, the built-in representation is descriptive, not necessarily presentation-ready.

Choosing a Format

Use this practical rule:

  • use HH:MM:SS for dashboards, timers, and logs
  • use explicit day formatting for long-running durations
  • use signed formatting when negative values are meaningful

Once the rule is chosen, keep one helper function for it instead of formatting timedeltas ad hoc in many places.

Keep Formatting Separate From Arithmetic

It is a good idea to keep duration calculations separate from the display layer. Compute with timedelta objects for as long as possible, and only convert to a string at the point where you need output. That avoids the common mistake of turning durations into strings too early and then having to parse them again later in the pipeline.

Common Pitfalls

  • Assuming str(td) always matches the presentation format you need.
  • Forgetting that durations longer than one day need an explicit decision about day handling.
  • Formatting negative timedeltas without normalizing the sign.
  • Using floating-point seconds when integer-second output is expected.
  • Duplicating slightly different timedelta-formatting logic across the codebase.

Summary

  • 'timedelta formatting is best handled with an explicit helper function.'
  • Convert total seconds and format the components you actually want.
  • Decide whether long durations should show total hours or explicit days.
  • Handle negative durations deliberately.
  • Use one consistent format per application context instead of relying on str(td).

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.