https://github.com/python/cpython/commit/18501a11e0358130a6bc48fee339ba3892e9e191 commit: 18501a11e0358130a6bc48fee339ba3892e9e191 branch: 3.13 author: Miss Islington (bot) <31488909+miss-isling...@users.noreply.github.com> committer: picnixz <10796600+picn...@users.noreply.github.com> date: 2025-05-10T15:57:29Z summary:
[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 efcc42ba70fb09333a2be16401da731662e2984b) Co-authored-by: Kentaro Jay Takahashi <64148935+kentaro...@users.noreply.github.com> files: M Doc/library/datetime.rst M Lib/test/datetimetester.py diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst index 708258a3d8dc9e..99a979038adb2c 100644 --- a/Doc/library/datetime.rst +++ b/Doc/library/datetime.rst @@ -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: diff --git a/Lib/test/datetimetester.py b/Lib/test/datetimetester.py index 952176bee632f7..44c5b28f455af0 100644 --- a/Lib/test/datetimetester.py +++ b/Lib/test/datetimetester.py @@ -762,6 +762,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)), _______________________________________________ Python-checkins mailing list -- python-checkins@python.org To unsubscribe send an email to python-checkins-le...@python.org https://mail.python.org/mailman3/lists/python-checkins.python.org/ Member address: arch...@mail-archive.com