datetimes, tzinfo and gmtime epoch
John Hunter
jdhunter at ace.bsd.uchicago.edu
Fri Apr 16 16:25:01 EDT 2004
>>>>> "John" == John Hunter <jdhunter at ace.bsd.uchicago.edu> writes:
John> I *think* this is correct, where x is a datetime instance
John> and tz is a tzinfo instance.
No goddawgy, I'm still off by an hour. Basically, I need to go from
datetime -> gm epoch time -> and back while properly accounting for
dst.
My converter class is below. The assertion fails, and the print
reveals I'm off by an hour.
Where is the timbot when you need him?
from your_tz_module import Eastern
import time
from datetime import datetime
SEC_PER_DAY = 24*3600
class PyDatetimeConverter:
"""
Convert python2.3 datetime instances to/from epoch gmtime
"""
def __init__(self, tz=Eastern):
self.tz = tz
def epoch(self, x):
'convert userland datetime instance x to epoch'
offset = self.tz.utcoffset(x).days*SEC_PER_DAY + \
self.tz.utcoffset(x).seconds
return time.mktime( x.timetuple() ) + offset
def from_epoch(self, e):
'return a datetime from the epoch'
y,month,d,h,m,s,wd,jd,ds = time.gmtime(e)
return datetime(y,month,d,h,m,s, tzinfo=self.tz)
tz = Eastern
dt1 = datetime(2004, 03, 01, tzinfo=tz) # before dst
dt2 = datetime(2004, 04, 15, tzinfo=tz) # after dst
dtc = PyDatetimeConverter(Eastern)
#assert( dtc.from_epoch( dtc.epoch(dt1) ) == dt1 )
print dt1, dt2
print dtc.from_epoch( dtc.epoch(dt1) ), dtc.from_epoch( dtc.epoch(dt2) )
More information about the Python-list
mailing list