Subclassing datetime.date does not seem to work

John Machin sjmachin at lexicon.net
Fri Apr 25 18:17:54 EDT 2008


On Apr 26, 7:43 am, Christian Heimes <li... at cheimes.de> wrote:
> Rick King schrieb:
>
>
>
> > I would like to subclass datetime.date so that I can write:
>
> > d = date2('12312008')
>
> > I tried:
>
> > from datetime import date
> > class date2(date):
> >     def __init__( self, strng ):
> >         mm,dd,yy = int(strng[:2]), int(strng[2:4]), int(strng[4:])
> >         date.__init__(self,yy,mm,dd)
>
> > But then this statement:
> > d = date2('12312008')
>
> > Causes:
> > TypeError: function takes exactly 3 arguments (1 given)
>
> > Is there something basically wrong with subclassing date?
> > -Rick King
>
> datetime.date is a C extension class. Subclassing of extension classes
> may not always work as you'd expect it.
>

... and in this case it's a sledgehammer to crack a nut:

>>> from datetime import date
>>> def date_from_string(strng):
...     mm, dd, yy = int(strng[:2]), int(strng[2:4]), int(strng[4:])
...     return date(yy, mm, dd)
...
>>> date_from_string('12312008')
datetime.date(2008, 12, 31)
>>>

Consider also:
>>> import datetime
>>> datetime.datetime.strptime('12312008', '%m%d%Y').date()
datetime.date(2008, 12, 31)




More information about the Python-list mailing list