jpayne@68: ''' jpayne@68: $Id: tzfile.py,v 1.8 2004/06/03 00:15:24 zenzen Exp $ jpayne@68: ''' jpayne@68: jpayne@68: from datetime import datetime jpayne@68: from struct import unpack, calcsize jpayne@68: jpayne@68: from pytz.tzinfo import StaticTzInfo, DstTzInfo, memorized_ttinfo jpayne@68: from pytz.tzinfo import memorized_datetime, memorized_timedelta jpayne@68: jpayne@68: jpayne@68: def _byte_string(s): jpayne@68: """Cast a string or byte string to an ASCII byte string.""" jpayne@68: return s.encode('ASCII') jpayne@68: jpayne@68: _NULL = _byte_string('\0') jpayne@68: jpayne@68: jpayne@68: def _std_string(s): jpayne@68: """Cast a string or byte string to an ASCII string.""" jpayne@68: return str(s.decode('ASCII')) jpayne@68: jpayne@68: jpayne@68: def build_tzinfo(zone, fp): jpayne@68: head_fmt = '>4s c 15x 6l' jpayne@68: head_size = calcsize(head_fmt) jpayne@68: (magic, format, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt, jpayne@68: typecnt, charcnt) = unpack(head_fmt, fp.read(head_size)) jpayne@68: jpayne@68: # Make sure it is a tzfile(5) file jpayne@68: assert magic == _byte_string('TZif'), 'Got magic %s' % repr(magic) jpayne@68: jpayne@68: # Read out the transition times, localtime indices and ttinfo structures. jpayne@68: data_fmt = '>%(timecnt)dl %(timecnt)dB %(ttinfo)s %(charcnt)ds' % dict( jpayne@68: timecnt=timecnt, ttinfo='lBB' * typecnt, charcnt=charcnt) jpayne@68: data_size = calcsize(data_fmt) jpayne@68: data = unpack(data_fmt, fp.read(data_size)) jpayne@68: jpayne@68: # make sure we unpacked the right number of values jpayne@68: assert len(data) == 2 * timecnt + 3 * typecnt + 1 jpayne@68: transitions = [memorized_datetime(trans) jpayne@68: for trans in data[:timecnt]] jpayne@68: lindexes = list(data[timecnt:2 * timecnt]) jpayne@68: ttinfo_raw = data[2 * timecnt:-1] jpayne@68: tznames_raw = data[-1] jpayne@68: del data jpayne@68: jpayne@68: # Process ttinfo into separate structs jpayne@68: ttinfo = [] jpayne@68: tznames = {} jpayne@68: i = 0 jpayne@68: while i < len(ttinfo_raw): jpayne@68: # have we looked up this timezone name yet? jpayne@68: tzname_offset = ttinfo_raw[i + 2] jpayne@68: if tzname_offset not in tznames: jpayne@68: nul = tznames_raw.find(_NULL, tzname_offset) jpayne@68: if nul < 0: jpayne@68: nul = len(tznames_raw) jpayne@68: tznames[tzname_offset] = _std_string( jpayne@68: tznames_raw[tzname_offset:nul]) jpayne@68: ttinfo.append((ttinfo_raw[i], jpayne@68: bool(ttinfo_raw[i + 1]), jpayne@68: tznames[tzname_offset])) jpayne@68: i += 3 jpayne@68: jpayne@68: # Now build the timezone object jpayne@68: if len(ttinfo) == 1 or len(transitions) == 0: jpayne@68: ttinfo[0][0], ttinfo[0][2] jpayne@68: cls = type(zone, (StaticTzInfo,), dict( jpayne@68: zone=zone, jpayne@68: _utcoffset=memorized_timedelta(ttinfo[0][0]), jpayne@68: _tzname=ttinfo[0][2])) jpayne@68: else: jpayne@68: # Early dates use the first standard time ttinfo jpayne@68: i = 0 jpayne@68: while ttinfo[i][1]: jpayne@68: i += 1 jpayne@68: if ttinfo[i] == ttinfo[lindexes[0]]: jpayne@68: transitions[0] = datetime.min jpayne@68: else: jpayne@68: transitions.insert(0, datetime.min) jpayne@68: lindexes.insert(0, i) jpayne@68: jpayne@68: # calculate transition info jpayne@68: transition_info = [] jpayne@68: for i in range(len(transitions)): jpayne@68: inf = ttinfo[lindexes[i]] jpayne@68: utcoffset = inf[0] jpayne@68: if not inf[1]: jpayne@68: dst = 0 jpayne@68: else: jpayne@68: for j in range(i - 1, -1, -1): jpayne@68: prev_inf = ttinfo[lindexes[j]] jpayne@68: if not prev_inf[1]: jpayne@68: break jpayne@68: dst = inf[0] - prev_inf[0] # dst offset jpayne@68: jpayne@68: # Bad dst? Look further. DST > 24 hours happens when jpayne@68: # a timzone has moved across the international dateline. jpayne@68: if dst <= 0 or dst > 3600 * 3: jpayne@68: for j in range(i + 1, len(transitions)): jpayne@68: stdinf = ttinfo[lindexes[j]] jpayne@68: if not stdinf[1]: jpayne@68: dst = inf[0] - stdinf[0] jpayne@68: if dst > 0: jpayne@68: break # Found a useful std time. jpayne@68: jpayne@68: tzname = inf[2] jpayne@68: jpayne@68: # Round utcoffset and dst to the nearest minute or the jpayne@68: # datetime library will complain. Conversions to these timezones jpayne@68: # might be up to plus or minus 30 seconds out, but it is jpayne@68: # the best we can do. jpayne@68: utcoffset = int((utcoffset + 30) // 60) * 60 jpayne@68: dst = int((dst + 30) // 60) * 60 jpayne@68: transition_info.append(memorized_ttinfo(utcoffset, dst, tzname)) jpayne@68: jpayne@68: cls = type(zone, (DstTzInfo,), dict( jpayne@68: zone=zone, jpayne@68: _utc_transition_times=transitions, jpayne@68: _transition_info=transition_info)) jpayne@68: jpayne@68: return cls() jpayne@68: jpayne@68: if __name__ == '__main__': jpayne@68: import os.path jpayne@68: from pprint import pprint jpayne@68: base = os.path.join(os.path.dirname(__file__), 'zoneinfo') jpayne@68: tz = build_tzinfo('Australia/Melbourne', jpayne@68: open(os.path.join(base, 'Australia', 'Melbourne'), 'rb')) jpayne@68: tz = build_tzinfo('US/Eastern', jpayne@68: open(os.path.join(base, 'US', 'Eastern'), 'rb')) jpayne@68: pprint(tz._utc_transition_times)