datetime objects and __new__()

peter peter.sabaini at gmail.com
Tue Nov 25 11:47:36 EST 2008


On Nov 25, 5:16 pm, Peter Otten <__pete... at web.de> wrote:
> peter wrote:
> >> >>> from datetime import *
> >> >>> class TS(datetime):
>
> >> ...     def __new__(cls, ts):
> >> ...             return datetime.fromtimestamp(ts)
> >> ...>>> TS(0)
>
> >> datetime.datetime(1970, 1, 1, 1, 0)
>
> >> works super() would be the most likely culprit.
>
> > Yes, that works, except the returned object is (unsurprisingly) a pure
> > datetime instance, which means I cannot access any other attributes I
> > defined on my class.
>
> How about
>
> import datetime
>
> class DT(datetime.datetime):
>     def __new__(cls, *args):
>         if len(args) == 1:
>             return cls.fromtimestamp(args[0])
>         return datetime.datetime.__new__(cls, *args)
>
> then?

A bit hacky, but does the trick quite nicely otherwise -- thanks :-)

Still, I wonder whats up with super(). Obviously I must be missing
something here.

peter.


>
> Peter




More information about the Python-list mailing list