Skip to content

gh-132642: Add documentation on how to render human-readable timedelta object #133825

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
May 10, 2025
16 changes: 16 additions & 0 deletions Doc/library/datetime.rst
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,22 @@ A :class:`timedelta` object represents a duration, the difference between two
>>> (d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)

Since the string representation of :class:`!timedelta` objects can be confusing,
use the following recipe to produce a more readable format:

.. code-block:: pycon

>>> def pretty_timedelta(td):
... if td.days >= 0:
... return str(td)
... return f'-({-td!s})'
...
>>> d = timedelta(hours=-1)
>>> str(d) # not human-friendly
'-1 day, 23:00:00'
>>> pretty_timedelta(d)
'-(1:00:00)'


Class attributes:

Expand Down
3 changes: 3 additions & 0 deletions Lib/test/datetimetester.py
Original file line number Diff line number Diff line change
Expand Up @@ -773,6 +773,9 @@ def test_str(self):
microseconds=999999)),
"999999999 days, 23:59:59.999999")

# test the Doc/library/datetime.rst recipe
eq(f'-({-td(hours=-1)!s})', "-(1:00:00)")

def test_repr(self):
name = 'datetime.' + self.theclass.__name__
self.assertEqual(repr(self.theclass(1)),
Expand Down
Loading