]> granicus.if.org Git - python/commitdiff
Issue #11576: Fixed timedelta subtraction glitch on big timedelta values
authorAlexander Belopolsky <alexander.belopolsky@gmail.com>
Wed, 6 Apr 2011 00:07:38 +0000 (20:07 -0400)
committerAlexander Belopolsky <alexander.belopolsky@gmail.com>
Wed, 6 Apr 2011 00:07:38 +0000 (20:07 -0400)
Lib/datetime.py
Lib/test/datetimetester.py
Modules/_datetimemodule.c

index 47e54ec2359174dbf7c4a8c008301565b2c53ecc..1ae7cb5305a02d252f7c840782dce664b3e4f66d 100644 (file)
@@ -485,7 +485,11 @@ class timedelta:
 
     def __sub__(self, other):
         if isinstance(other, timedelta):
-            return self + -other
+            # for CPython compatibility, we cannot use
+            # our __class__ here, but need a real timedelta
+            return timedelta(self._days - other._days,
+                             self._seconds - other._seconds,
+                             self._microseconds - other._microseconds)
         return NotImplemented
 
     def __rsub__(self, other):
index e9ceee6d961609568c97277d819eccfb7e57f8bb..38f3b8f19bd95a9c8527d692ff82f810cfc90100 100644 (file)
@@ -383,6 +383,12 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
         for i in range(-10, 10):
             eq((i*us/-3)//us, round(i/-3))
 
+        # Issue #11576
+        eq(td(999999999, 86399, 999999) - td(999999999, 86399, 999998),
+           td(0, 0, 1))
+        eq(td(999999999, 1, 1) - td(999999999, 1, 0),
+           td(0, 0, 1))
+
     def test_disallowed_computations(self):
         a = timedelta(42)
 
index 61959405e881a5d296df674ba559d1ad3ff009bf..6ee531768a55b44358b55ca1371e4a6427fcf22a 100644 (file)
@@ -1801,13 +1801,14 @@ delta_subtract(PyObject *left, PyObject *right)
 
     if (PyDelta_Check(left) && PyDelta_Check(right)) {
         /* delta - delta */
-        PyObject *minus_right = PyNumber_Negative(right);
-        if (minus_right) {
-            result = delta_add(left, minus_right);
-            Py_DECREF(minus_right);
-        }
-        else
-            result = NULL;
+        /* The C-level additions can't overflow because of the
+         * invariant bounds.
+         */
+        int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
+        int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
+        int microseconds = GET_TD_MICROSECONDS(left) -
+                           GET_TD_MICROSECONDS(right);
+        result = new_delta(days, seconds, microseconds, 1);
     }
 
     if (result == Py_NotImplemented)