Menu

#274 Sourcecode for 'TimeDelta_or_None' contains errors

MySQLdb-1.2
closed
MySQLdb (285)
5
2012-09-19
2008-12-31
No

This is for version 1.2.2 of MySQLdb
Given lack of documentation of the function, the second part of this bug is based on an assumption.

Two things seem to be rather wrong with the code around the times.TimeDelta_or_None function.

1) At line 63 there is a comparison of variable 'h' with 0, which determines whether to return the timedelta or an inverted timedelta. The bug lies in the fact that 'h' at that point is a string, and thus always compares larger than an integer.

2) This is based on the assumption that a timedelta string '-1:14:30' is the inverse of '1:14:30'. 12:00:00Z + '-1:14:30' results into 10:45:30Z according to this.

The problem is that the function in its current form creates a timedelta for negative 1 hour, and then positive 14 minutes 30 seconds, resulting in negative 45 minutes 30 seconds.

Below is the code I use in my own module that does what I suspect TimeDelta_or_None should do:

try:
hour, minute, second = string.split(':')
micro, second = math.modf(float(second))
timedelta = datetime.timedelta(
hours=abs(int(hour)), minutes=int(minute),
seconds=int(second), microseconds=int(micro * 1000000))
return (-1, 1)[int(hour) > 0] * timedelta
except:
return None

Discussion

  • Elmer de Looff

    Elmer de Looff - 2009-01-10

    According to the Python documentation on datetime.timedelta, there is no need to manually "sort out" the natural and decimal parts of the seconds because:

    "If any argument is a float and there are fractional microseconds, the fractional microseconds left over from all arguments are combined and their sum is rounded to the nearest microsecond. If no argument is a float, the conversion and normalization processes are exact (no information is lost)."

    This means that the code in your patch could be reduced to:

    • h, m, s = int(h), int(m), float(s)
    • return time(hour=h, minute=m, second=s)

    Unfortunately the datetime.time object isn't as nice and won't support fractional seconds.
    Depending on how great consistency is valued, it might be worth it to keep both functions as they are

     
  • Andy Dustman

    Andy Dustman - 2009-03-11

    Fixed in SVN, will appear in 1.2.3b2 or later

     
  • Kyle VanderBeek

    Kyle VanderBeek - 2010-06-17

    Closing out, fix is in 1.2.3.

     

Log in to post a comment.