[Python-Dev] datetime module enhancements

Collin Winter collinw at gmail.com
Fri Mar 9 22:14:42 CET 2007


On 3/9/07, Collin Winter <collinw at gmail.com> wrote:
> On the subject of datetime enhancements, I came across an SF patch
> (#1673403) the other day that proposed making it possible to compare
> date and datetime objects. Quoting from the patch summary:
>
> """
> Comparing a date to a datetime currently throws an exception. This makes no
> sense. In what way is:
>
> datetime(2006, 1, 1, 0, 0, 0) < date(2007, 1, 1)
>
> not a perfectly reasonable and well-defined comparison? Throwing an
> exception here violates the "Principle of Least Surprise" to a considerable
> degree.
>
> Obviously some slight ambiguity arises if the date and the datetime differ
> only in the time part. There are two sensible responses in this situation
> that I can see:
>
> Treat dates as if they have a time-part of midnight. This is my preferred
> solution, and it is already what the datetime module does, for example,
> when subtracting two dates.
>
> Treat dates as if they refer to the entire day, i.e. if the date and
> datetime differ only in the time part then they are equal. This is
> consistent but becomes confusing in other situations such as when
> subtracting dates.
> """
>
> Any thoughts on this?

One solution that just occurred to me -- and that skirts the issue of
choosing an interpretation -- is that, when comparing date and
datetime objects, the datetime's .date() method is called and the
result of that call is compared to the original date. That is,

datetime_obj < date_obj

is implicitly equivalent to

datetime_obj.date() < date_obj

Seems a ready-made use case for that method.

Collin Winter


More information about the Python-Dev mailing list