From: Kenneth M. <kmm...@wi...> - 2004-04-27 07:11:51
|
I've been using matplotlib for some plotting involving dated values, but wasn't able to figure out how to use the new plot_date with log axes. (I'm still a rank newbie at matplotlib.) It struck me that an integer that "knew" it represented seconds since the epoch would be a neat way of feeding matplotlib's non-date functions the values they expected, while at the same time manipulating dates in my own code; and, since I'd just done a bit of reading of new-style classes in Python, came up with the following: import datetime, time class intdate(int): '''Subclasses int for use as dates.''' def __init__(self, ordinal): int.__init__(self, ordinal) self.__date = datetime.date.fromtimestamp(ordinal) day = property(fget=lambda self:self.__date.day) month = property(fget=lambda self:self.__date.month) year = property(fget=lambda self:self.__date.year) def isoformat(self): return self.__date.isoformat() def timetuple(self): return self.__date.timetuple() def date(self): return self.__date def epoch(x): 'convert userland datetime instance x to epoch' return time.mktime(x.timetuple()) def date(year, month, day): return intdate(epoch(datetime.date(year, month, day))) def today(): return intdate(epoch(datetime.date.today())) Use 'today' and 'date' to create intdate instances. They can be used in python wherever you would normally use an integer (I believe), but can also be treated as instances of the intdate class. They can't be used in numarry/numeric of course, and certainly aren't suited for use with large data sets, but I thought this was sorta neat, in a nasty hacky kind of way. You could of course expand the indate class; my needs were simple. It would also be simple to reimplement some of the functions so an internal instance of datetime wasn't necessary... Too bad there isn't a standard C primitive type for representing dates in some standardized numeric format, such as the epoch style. But I thought some people might find this useful and/or informative Cheers, Ken |