]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-132642: document how to render human-readable `timedelta` objects (GH-13382...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sat, 10 May 2025 15:57:29 +0000 (17:57 +0200)
committerGitHub <noreply@github.com>
Sat, 10 May 2025 15:57:29 +0000 (15:57 +0000)
gh-132642: document how to render human-readable `timedelta` objects (GH-133825)
(cherry picked from commit efcc42ba70fb09333a2be16401da731662e2984b)

Co-authored-by: Kentaro Jay Takahashi <64148935+KentaroJay@users.noreply.github.com>
Doc/library/datetime.rst
Lib/test/datetimetester.py

index 708258a3d8dc9e57d33f20a38320e2fc728e308f..99a979038adb2c6950edfd818b857969e3c4a3ee 100644 (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:
 
index 952176bee632f7084da6195364beac30b0887414..44c5b28f455af0c51882f7644058e01ad5afe015 100644 (file)
@@ -762,6 +762,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)),