Skip to content

Commit 18501a1

Browse files
[3.13] gh-132642: document how to render human-readable timedelta objects (GH-133825) (#133836)
gh-132642: document how to render human-readable `timedelta` objects (GH-133825) (cherry picked from commit efcc42b) Co-authored-by: Kentaro Jay Takahashi <[email protected]>
1 parent 5afb224 commit 18501a1

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

Doc/library/datetime.rst

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,22 @@ A :class:`timedelta` object represents a duration, the difference between two
261261
>>> (d.days, d.seconds, d.microseconds)
262262
(-1, 86399, 999999)
263263

264+
Since the string representation of :class:`!timedelta` objects can be confusing,
265+
use the following recipe to produce a more readable format:
266+
267+
.. code-block:: pycon
268+
269+
>>> def pretty_timedelta(td):
270+
... if td.days >= 0:
271+
... return str(td)
272+
... return f'-({-td!s})'
273+
...
274+
>>> d = timedelta(hours=-1)
275+
>>> str(d) # not human-friendly
276+
'-1 day, 23:00:00'
277+
>>> pretty_timedelta(d)
278+
'-(1:00:00)'
279+
264280
265281
Class attributes:
266282

Lib/test/datetimetester.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -762,6 +762,9 @@ def test_str(self):
762762
microseconds=999999)),
763763
"999999999 days, 23:59:59.999999")
764764

765+
# test the Doc/library/datetime.rst recipe
766+
eq(f'-({-td(hours=-1)!s})', "-(1:00:00)")
767+
765768
def test_repr(self):
766769
name = 'datetime.' + self.theclass.__name__
767770
self.assertEqual(repr(self.theclass(1)),

0 commit comments

Comments
 (0)