DZone 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
Another Simple Datetime+struct_time Class
I had shown how datetime can be used in python 2.2
in a <a href=http://www.bigbold.com/snippets/posts/show/1614>previous snippet</a>. 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()).
import time
class datetime(object):
def __init__(self, *argv):
self.t = time.struct_time(argv+(0,)*(9-len(argv))) # append to length 9
def __getattr__(self, name):
try:
i = ['year', 'month', 'day', 'hour', 'minute', 'second', 'weekday'].index(name)
return self.t[i]
except:
return getattr(self.t, name)
def __len__(self): return len(self.t)
def __getitem__(self, key): return self.t[key]
def __repr__(self): return repr(self.t)
def now(self=None):
return datetime(*time.localtime())
now = staticmethod(now)
def strftime(self, fmt="%Y-%m-%d %H:%M:%S"):
return time.strftime(fmt, self.t)
Here's its usage
# here it works like datetime.datetime() >>> t = datetime.now() >>> t.year, t.month, t.day (2006, 3, 13) >>> t.hour, t.minute, t.second (23, 3, 28) # but also works like localtime() >>> t (2006, 3, 13, 23, 3, 28, 0, 72, -1) >>> t.tm_year, t[0] (2006, 2006) >>> mktime(t) 1142265808.0 # good default for strftime (= ctime) >>> t.strftime() '2006-03-13 23:03:28'





