MySQLdb1 icon indicating copy to clipboard operation
MySQLdb1 copied to clipboard

TimeDiffs with negative duration and zero hours have wrong sign

Open rawatson opened this issue 10 years ago • 1 comments

The following script should print a negative time value (-1 day, 23:30:00) but instead prints a positive one (0:30:00)

#!/usr/bin/env python
import MySQLdb

db = MySQLdb.connect('YOUR CONNECTION INFO HERE')
query = '''SELECT TIMEDIFF('20:30:00','21:00:00')''';
cur = db.cursor()
cur.execute(query)

for row in cur.fetchall():
    print(row[0])

The issue is in times.py, in the TimeDelta_or_None function:

def TimeDelta_or_None(s):
    try:
        h, m, s = s.split(':')
        if '.' in s:
            s, ms = s.split('.')
            ms = ms.ljust(6, '0')
        else:
            ms = 0
        h, m, s, ms = int(h), int(m), int(s), int(ms)
        td = timedelta(hours=abs(h), minutes=m, seconds=s,
                       microseconds=ms)
        if h < 0:
            return -td
        else:
            return td
    except ValueError:
        # unpacking or int/float conversion failed
        return None

Normally, when a negative time is given, h will be negative, and the correct result will be returned. However, when s is something like -00:30:00, h will be set to int('-00'), which will be equal to 0. The test h < 0 will then fail, and an incorrect result will be returned.

rawatson avatar Apr 21 '14 06:04 rawatson

@rawatson can you check my commit in real project?

tyzhnenko avatar Apr 21 '14 23:04 tyzhnenko