oddities in the datetime module

Max M maxm at mxm.dk
Fri Jan 14 11:09:12 CET 2005


# -*- coding: latin-1 -*-

"""

I am currently using the datetime package, but I find that the design is 
oddly
asymmetric. I would like to know why. Or perhaps I have misunderstood 
how it should be used?

I can make a datetime easily enough

 >>> datetime(2005, 1, 1)
datetime.datetime(2005, 1, 1, 0, 0)

What I find odd is that I cannot make a new datetime object from the 
timetuple()
like this:

 >>> d1 = datetime(2005, 1, 1, 12, 13, 10)
 >>> d2 = datetime(*d1.timetuple())
Traceback (most recent call last):
     ...
TypeError: function takes at most 8 arguments (9 given)
 >>> d1.timetuple()
(2005, 1, 1, 12, 13, 10, 5, 1, -1)

Because if I subclass datetime, I often need to convert between my 
subclass and
the built in datetime module. But there is no direct way to do it.

Instead I have to do it in a somewhat more clunky way:

 >>> datetime(* (d1.timetuple()[:6] + (0, d1.tzinfo)))
datetime.datetime(2005, 1, 1, 12, 13, 10)

if I want to convert a date to a datetime it is easy, even though I 
still have
to truncate the timetuple.

 >>> d = date(2005, 1, 1)
 >>> datetime(*d.timetuple()[:6])
datetime.datetime(2005, 1, 1, 0, 0)

The other way around is also easy.

 >>> dt = datetime(2005, 1, 1, 12, 0, 0)
 >>> date(*dt.timetuple()[:3])
datetime.date(2005, 1, 1)

But it's a clunky design that I have to do it that way.

I think it would be nice if date and datetime at least had a pair of
datetimetuple() and from_datetimetuple() methods that could be used for 
easily
converting between datetime types. Like the ones I have made below.

That would make them a lot more symmetric.

 >>> datetimetuple = (2005,1,1,12,0,0,0,None)
 >>> datetime2.from_datetimetuple(datetimetuple)
datetime2(2005, 1, 1, 12, 0)

 >>> dtt = datetime2(2005,1, 1).datetimetuple()
 >>> dtt
(2005, 1, 1, 0, 0, 0, 0, None)

 >>> d2 = date2.from_datetimetuple(dtt)
 >>> d2
date2(2005, 1, 1)

 >>> datetime2.from_datetimetuple(d2.datetimetuple())
datetime2(2005, 1, 1, 0, 0)

"""


from datetime import datetime, date

class datetime2(datetime):

     def datetimetuple(self):
         return self.timetuple()[:6] + (0, self.tzinfo)

     def from_datetimetuple(dt_tuple):
         return datetime2(*dt_tuple)
     from_datetimetuple = staticmethod(from_datetimetuple)


class date2(date):

     def datetimetuple(self):
         return self.timetuple()[:6] + (0, None)

     def from_datetimetuple(dt_tuple):
         return date2(*dt_tuple[:3])
     from_datetimetuple = staticmethod(from_datetimetuple)




#from datetime import datetime
#
#ical = Calendar()
#print ical.ical()

if __name__ == "__main__":

     import os.path, doctest, x
     # import and test this file
     doctest.testmod(x)


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science



More information about the Python-list mailing list