farcepest / MySQLdb1

MySQL database connector for Python (legacy version)
https://sourceforge.net/projects/mysql-python/
667 stars 318 forks source link

TimeDiffs with negative duration and zero hours have wrong sign #63

Open rawatson opened 10 years ago

rawatson commented 10 years ago

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.

tyzhnenko commented 10 years ago

@rawatson can you check my commit in real project?