comparing DateTime instances

Mark McEahern mark at mceahern.com
Fri Feb 1 17:29:56 EST 2002


I think I just need a sanity check.  I'm trying to compare DateTime
instances (from the eGenix mx.DateTime package).

$ python
Python 2.2 (#1, Dec 31 2001, 15:21:18)
[GCC 2.95.3-5 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> expected = "2003-01-31 14:13:13.65"
>>> actual = "2003-01-31 14:13:13.65"
>>> from mx.DateTime import DateFrom, cmp
>>> e = DateFrom(expected)
>>> a = DateFrom(actual)
>>> cmp(a, e)
0

I think this is telling me that a and e are equal.  I'm still trying to get
my brain to instantly recognize the seemingly flipped around semantics of
cmp.  I understand that __cmp__ returns 0 for equality--and that 1 and -1
are used to indicate less-than, greater-than ordering.  So too for cmp, eh?

So that would mean, if I were comparing two DateTime instances in a unit
test and I wanted the test to fail if the dates were NOT equal, I might say
something like this:

	self.failIf(cmp(date1, date2))

If date1 equals date2 (I know I can use accuracy to account for fuzziness),
cmp will return 0, which is the same as false, and therefore failIf passes
because it only fails if the argument is true.

The documentation for mx.DateTime's cmp seems to assume the reader
understands __cmp__.  This is all we find there:

"cmp(obj1,obj2,accuracy=0.0)
Compares two DateTime[Delta] objects.
If accuracy is given, then equality will result in case the absolute
difference between the two values is less than or equal to accuracy."

Perhaps this could expand on the actual set of results:

-1 : obj1 is less than obj2
 0 : obj1 is equal to obj2
 1 : obj1 is greater than obj2

It wouldn't seem to hurt and it might avoid someone else wondering the same
silly things I'm wondering.

Thanks,

// mark





More information about the Python-list mailing list