comparing datetime with date

Robert Brewer fumanchu at amor.org
Wed Sep 15 11:42:46 EDT 2004


Donnal Walter wrote:
> Perhaps I am guilty of not explaining what I was trying to 
> do. I have an 
> abstract class (called Cell) that implements a form of the observable 
> pattern. When x.set(...) is called, it check to see if the 
> new value is 
> different from the old value before making the change and notifying 
> observers. The abstract Cell class has a lot of other 
> functionality, as 
> well, but this is the critical feature. Then I have at least three 
> subclasses: one for text (strings), one for numbers, and one for 
> timepoints. Althought the internal value representation is 
> different for 
> all three, they all use the same basic set(...) method. In my first 
> implementation, the internal representation for TimePoint was 
> going to 
> be a datetime.datetime object. Sometimes, however, one knows a date 
> without knowing the time (date of birth, for example, before 
> knowing the 
> time of birth, and this is important in newborn intensive care). I 
> wanted to be able to enter the date of birth in a way that indicates 
> that the time is unknown at present, so I used a datetime.date. Then 
> later after the actual time is learned, it could be changed to a 
> datetime.datetime. How else would the associated presenter 
> (presentation 
> object) know whether or not the time was unknown? But this means that 
> for my implementation dt.date should not evaluate as equal to the 
> corresponding dt.datetime.
> 
> My solution now (as a result of this thread) is to use a 
> three-tuple for 
> date of birth and a five-tuple for date and time of birth. These two 
> representations obviously do evaluate as different. I still 
> convert to 
> datetime.datetime (with or without DST information) for 
> calculations of 
> intervals, but storage is the basic time tuple.

Given your birthdate/time example, I'd look seriously at providing four
Cell subclasses: str, int, date, and time. Separating date and time
completely allows either to be None (= unknown). If consumer code needs
to compare both date and time, you can then write:

import datetime

class Thing(object):
    def __init__(self, d, t):
        self.d = DateCell(d)
        self.t = TimeCell(t)

    def dt(self):
        return datetime.datetime.combine(self.d, self.t)

x = Thing(datetime.date(2004, 9, 15), None)
y = Thing(datetime.date(2004, 9, 15), datetime.time(11, 59))
if x.dt == y.dt:
    do_stuff()

...the 'if' statement will then raise TypeError, since x.t is None and
won't combine. You can then trap that either inside or outside the dt()
method and handle it as you like.

Just a thought.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list