Can't subclass datetime.datetime?

Steven Bethard steven.bethard at gmail.com
Mon Feb 14 15:06:48 EST 2005


Grant Edwards wrote:
> Is it true that a datetime object can convert itself into a
> string, but not the other way around?  IOW, there's no simple
> way to take the output from str(d) and turn it back into d?

I assume this is true because there is not one standard format for a 
date-time string.  But I don't use the module enough, so I'll let 
someone else answer this part of the question.

> import datetime
> 
> class MyDatetime(datetime.datetime):
>     def __init__(self,s):
>             s1,s2 = s.split(' ')
>             v = s1.split('-') + s2.split(':')
>             v = map(int,v)
>             datetime.datetime.__init__(self,v[0],v[1],v[2],v[3],v[4],v[5])
> 
> s = '2005-02-14 12:34:56'
> d = MyDatetime(s)
> 
> Running the above yields:
> 
>   Traceback (most recent call last):
>     File "dt.py", line 11, in ?
>       d = MyDatetime(s)
>   TypeError: function takes at least 3 arguments (1 given)

datetime.datetime objects are immutable, so you need to define __new__ 
instead of __init__:

py> class DateTime(datetime.datetime):
...     def __new__(cls, s):
...         s1, s2 = s.split(' ')
...         v = map(int, s1.split('-') + s2.split(':'))
...         return datetime.datetime.__new__(cls, *v)
...
py> DateTime('2005-02-14 12:34:56')
DateTime(2005, 2, 14, 12, 34, 56)

Steve



More information about the Python-list mailing list