[Dev] consequences of date and times types switchover

Phillip J. Eby pje at telecommunity.com
Fri May 27 16:10:01 PDT 2005


At 03:28 PM 5/27/2005 -0700, Andi Vajda wrote:

>With the recent change from mx date/time types to the python builtins 
>there are few new constraints to keep in mind. The python builtins are 
>more strict in several ways, some unfortunate:
>
>   - You cannot compare a date with a datetime object (and vice-versa) and 
> that
>     is very unfortunate as to work this around you have to either:
>        - write custom comparison code
>        - initialize a datetime from the date by leaving the datetime time
>          fields 0 which leads to the next problem

To compare a date with a datetime, use the datetime's '.date()' method to 
downcast to a date; Python won't do the comparison because of the implicit 
loss in precision.

So, if you spot a type error in a date comparison, and you're trying to 
compare a simple date with a datetime, you need to convert the datetime to 
a date, first.


>   - You cannot compare datetimes or times that are not the same in their
>     'naivete' (to use some unfortunate python terminology here, a datetime is
>     considered 'naive' when it doesn't have a time zone). When creating a
>     datetime from a date for sake of comparison you don't have a timezone to
>     initialize that datetime with since a date has no such thing, by
>     definition.
>
>The calendar code (and its UI) is still working with the previous, 
>mx-based, assumptions. I couldn't fix that as it was very hard to know 
>where what was intended to do and work with, especially regarding the use 
>of timezones which is still being spec'ed out.

As each of these comparisons occurs at runtime, we'll get errors showing 
where to fix them, so it shouldn't be a big deal to get them taken care of.


>This message is just a heads up. For example, if you import the demo 
>calendar, when you render it, you get exactly such an error (about 
>timezone and no timezone types being compared). I did send a patch to 
>Morgen working this around with custom comparison methods but wasn't sure 
>that was the right approach.

What does it mean to compare at time with a timezone, with a time with no 
timezone?  If you want to treat a naive timestamp as one in the "local" 
timezone, you can do:

     aDateTime.replace(tzinfo=tzlocal)

(assuming you have a 'tzlocal' variable with a dateutil 'tzlocal()' 
timezone instance in it.)

It might be better to make such conversions explicit.


>It would all be easier from the standpoint of the calendar code if there 
>was a simple way to say test today < datetime < tomorrow but there doesn't 
>seem to be such a thing, or maybe I'm missing something ? Phillip, do you 
>know ?

Yes, the conversion you want for that example is 'aDatetime.date() == today'.



More information about the Dev mailing list