[Python-Dev] Curious datetime method

Alexander Belopolsky alexander.belopolsky at gmail.com
Tue Jul 20 17:56:47 CEST 2010


On Tue, Jul 20, 2010 at 9:57 AM, Anders Sandvig
<anders.sandvig at gmail.com> wrote:
>> I wonder why would anyone want to use datetime.today() instead of
>> datetime.now()?
>
> Because this method is also present in datetime.date. Thus, you can
> reference stuff like  d.today().day without caring whether d is a date
> or a datetime object.

For this particular use it is not necessary for today() method to have
covariant returns.  In other words, if datetime.today() returned a
date object in the same way as date.today() does, you could still
write  d.today().day.  Moreover, since today() is a class method, the
result does not depend on d, so you can simply do date.today().day.

A more interesting use case would be a function that tells whether d
is in the future:

def isfuture(d):
      return d > d.today()

Here covariant return is necessary because you cannot compare datetime
to date and even if you could, this is probably not what you want in
this case.

This implementation of isfuture() has a problem: it does not work with
aware datetime objects.  To make that work, we would need today(tz)
method that can account for a timezone, or better have now(tz=None)
available as a date class method:

def isfuture(d):
      return d > d.now(d.tzinfo)

Furthermore, this use case does not explain the need to have
datetime.today() respect overriding of fromtimestamp() in datetime
subclasses or having to reproduce datetime.fromtimestamp(time.time())
with all its undefined behavior that comes with floating point
timestamps.

In the ideal world, I would like today() to accept tz and always
return date object while adding "covariant" now([tz]) method to date
and possibly even time class.  (The later is the subject of
http://bugs.python.org/issue8902).

In the real world where we have to take backward compatibility into
account, I would like to make today() and now() to be the same: both
taking optional tz argument, both available as either date or datetime
methods and both covariant.  the justification for having two methods
doing exactly the same will be just readability: date.today() and
datetime.now() are more readable than date.now() and datetime.today().


More information about the Python-Dev mailing list