Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Another simple datetime+struct_time class

I had shown how datetime can be used in python 2.2
in a previous snippet. Still, it's sometimes too big.

Here's a minimal implementation. It works like both
datetime and stuct_time (as returned by localtime() and gmtime()).
   1  
   2  import time
   3  
   4  class datetime(object):
   5      def __init__(self, *argv):
   6          self.t = time.struct_time(argv+(0,)*(9-len(argv)))    # append to length 9 
   7      def __getattr__(self, name):
   8          try:
   9              i = ['year', 'month', 'day', 'hour', 'minute', 'second', 'weekday'].index(name)
  10              return self.t[i]
  11          except:
  12              return getattr(self.t, name)
  13      def __len__(self): return len(self.t)
  14      def __getitem__(self, key): return self.t[key]
  15      def __repr__(self): return repr(self.t)
  16      def now(self=None):
  17          return datetime(*time.localtime())
  18      now = staticmethod(now)
  19      def strftime(self, fmt="%Y-%m-%d %H:%M:%S"):
  20          return time.strftime(fmt, self.t)

Here's its usage
   1  
   2  # here it works like datetime.datetime()
   3  >>> t = datetime.now()
   4  >>> t.year, t.month, t.day
   5  (2006, 3, 13)
   6  >>> t.hour, t.minute, t.second
   7  (23, 3, 28)
   8  
   9  # but also works like localtime()
  10  >>> t
  11  (2006, 3, 13, 23, 3, 28, 0, 72, -1)
  12  >>> t.tm_year, t[0]
  13  (2006, 2006)
  14  >>> mktime(t)
  15  1142265808.0
  16  
  17  # good default for strftime (= ctime)
  18  >>> t.strftime()
  19  '2006-03-13 23:03:28'

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS