oddities in the datetime module

Tim Peters tim.peters at gmail.com
Fri Jan 14 18:20:57 EST 2005


[Max M]
> ...
> First of, it should be possible to easily convert between the
> datetime objects.

Why?  All the conversions people asked for when the module was being
designed were implemented.

> And eg. the date object doesn't have a datetime() method. Which
> it could easily have.

But not a *sensible* one.  If you only have a date (or time), what's a
conversion to datetime supposed to do about the "missing values"? 
Guess?  No good.

> Neither does time. They could have. But I don't think that
> is the way to solve it.

datetime.datetime objects have .date() and .time() methods, returning
the obvious datetime.date and datetime.time slices of the
datetime.datetime.  The class constructor datetime.combine() goes in
the other direction, building a datetime.datetime object by combining
a datetime.date and a datetime.time.

> It is a problem if you make a subclass of datetime. Often you
> will ned to make datetime arithmetics with the new class.
>
> Like: datetime_subclass_1 + datetime_subclass_2
>
> The result of that is a plain datetime

If your subclass doesn't override __add__, yes.

> In that case you will rather want your own subclass returned.

While possible, that's not necessarily so of all subclasses.

> But subclasses of datetime returns datetime objects.  Not the
> subclass.

That depends on whether the subclass overrides __add__, and if so, the
code in its __add__ method.

> So to do an add of your own objects you must convert the output
> to your own class "manually"
>
> class my_datetime(datetime):
> 
>     def __add__(self, other):
>         result = datetime.__add__(self, other)
>         return my_datetime(result.timetuple()[:6])
> 
> datetime(), time() etc. methods will not help with this.

Well, it's unclear where you think you need help there.  If that's
what you want your subclass __add__ to do, you've already done it,
right?  It could save tedium to give your subclass a class
constructor, e.g., from_datetime(), and then code __add__ as

def __add__(self, other):
    return my_datetime.from_datetime(datetime.__add__(self, other))

Whether the implementation wants to use timetuple() depends on what
the subclass wants to do; for example, a subclass that intends to
support a notion of time zone needs more than just that.



More information about the Python-list mailing list