comparing datetime with date
Donnal Walter
donnal at donnal.net
Tue Sep 14 18:00:35 EDT 2004
Peter Hansen wrote:
> Diez B. Roggisch wrote:
>
>> Donnal Walter wrote:
>>
>>> How can these two objects be considered equal? Is there a *general* way
>>> to test for date != datetime as well as 4.5 != 4.6?
>>
>>
>> Try making a datetime-object from your date, with zeros for the time
>> part -
>> then you'll get what you want.
>
>
> While trying to provide my first answer, I thought of suggesting
> this, but there doesn't appear to be a simple way of doing it.
> It looked like the following was the best I could do (where 'x'
> is a datetime.date object):
>
> z = datetime.datetime(x.year, x.month, x.day)
>
> I just found timetuple(), which means this could be written
> in the awful form:
>
> z = datetime.datetime(*x.timetuple()[:3])
>
> but that's hardly better, and definitely more inscrutable.
>
> To answer Donnal's question above, however, it appears this
> might be a reasonable approach:
>
> >>> x.timetuple() == y.timetuple()
> False
>
> Not sure there's a better approach readily available.
>
> -Peter
Thanks for the suggestions. I have decided *not* to store date/datetime
objects, but rather store the corresponding time tuples: 3-tuple for
date only, and 5- or 6-tuple for date and time, depending on whether or
not seconds are given). Then the following method notifies observers if
a simple date is changed to the date with time (just like number changes
and string changes).
def set(self, value):
if value != self._state: # now this works!
self._state = value
self.notify_observers(self)
This means, of course, that if an observer wants to calculate a
TimeDelta, the corresponding datetimes have to be constructed, but I
don't think this is too inefficient.
time1 = datetime.datetime(*time1.get()) # 3-, 5-, or 6-tuple
time2 = datetime.datetime(*time2.get())
tdelta = time2 - time1
The observer object (and user) would need to understand the loss of
precision when times are not actually given, but at least the relevant
methods work regardless.
Thanks again,
Donnal Walter
Arkansas Children's Hospital
More information about the Python-list
mailing list