Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions src/MySQLdb/times.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
9 changes: 8 additions & 1 deletion tests/test_MySQLdb_times.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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"
Expand Down
Loading