diff --git a/src/MySQLdb/times.py b/src/MySQLdb/times.py index f304ec7b..a920cb30 100644 --- a/src/MySQLdb/times.py +++ b/src/MySQLdb/times.py @@ -38,10 +38,20 @@ def TimestampFromTicks(ticks): def format_TIMEDELTA(v): - seconds = int(v.seconds) % 60 - minutes = int(v.seconds // 60) % 60 - hours = int(v.seconds // 3600) % 24 - return "%d %d:%d:%d" % (v.days, hours, minutes, seconds) + # Negative timedeltas store the sign in days and keep seconds positive. + # Format the absolute value so the sign is not applied twice by MySQL. + sign = "" + if v.days < 0: + sign = "-" + v = abs(v) + + micros = v.microseconds + minutes, seconds = divmod(v.seconds, 60) + hours, minutes = divmod(minutes, 60) + + if micros: + return f"{sign}{v.days} {hours}:{minutes}:{seconds}.{micros:06d}" + return f"{sign}{v.days} {hours}:{minutes}:{seconds}" def format_TIMESTAMP(d): diff --git a/tests/test_MySQLdb_times.py b/tests/test_MySQLdb_times.py index 7fc4e21b..8b3509ed 100644 --- a/tests/test_MySQLdb_times.py +++ b/tests/test_MySQLdb_times.py @@ -120,6 +120,7 @@ def test_datetime_to_literal(self): def test_datetimedelta_to_literal(self): d = datetime(2015, 12, 13, 1, 2, 3) - datetime(2015, 12, 13, 1, 2, 2) assert times.DateTimeDelta2literal(d, "") == b"'0 0:0:1'" + assert times.DateTimeDelta2literal(-timedelta(minutes=30), "") == b"'-0 0:30:0'" class TestFormat(unittest.TestCase): @@ -131,7 +132,13 @@ def test_format_timedelta(self): assert times.format_TIMEDELTA(d) == "0 2:2:2" d = datetime(2015, 1, 1, 10, 11, 12) - datetime(2015, 1, 1, 11, 12, 13) - assert times.format_TIMEDELTA(d) == "-1 22:58:59" + assert times.format_TIMEDELTA(d) == "-0 1:1:1" + + assert times.format_TIMEDELTA(-timedelta(minutes=30)) == "-0 0:30:0" + assert times.format_TIMEDELTA(-timedelta(days=1, hours=2)) == "-1 2:0:0" + d = timedelta(seconds=83579, microseconds=51000) + assert times.format_TIMEDELTA(d) == "0 23:12:59.051000" + assert times.format_TIMEDELTA(-d) == "-0 23:12:59.051000" def test_format_timestamp(self): assert times.format_TIMESTAMP(datetime(2015, 2, 3)) == "2015-02-03 00:00:00"