[3.14] gh-132642: document how to render human-readable timedelta objects (GH-133825) (#133837)

gh-132642: document how to render human-readable `timedelta` objects (GH-133825)
(cherry picked from commit efcc42ba70)

Co-authored-by: Kentaro Jay Takahashi <64148935+KentaroJay@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2025-05-10 18:00:36 +02:00 committed by GitHub
parent 6dc12dad4b
commit 13c94d0401
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 19 additions and 0 deletions

View file

@ -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:

View file

@ -773,6 +773,9 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
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)),