tzfile.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. '''
  2. $Id: tzfile.py,v 1.8 2004/06/03 00:15:24 zenzen Exp $
  3. '''
  4. from datetime import datetime
  5. from struct import unpack, calcsize
  6. from pytz.tzinfo import StaticTzInfo, DstTzInfo, memorized_ttinfo
  7. from pytz.tzinfo import memorized_datetime, memorized_timedelta
  8. def _byte_string(s):
  9. """Cast a string or byte string to an ASCII byte string."""
  10. return s.encode('ASCII')
  11. _NULL = _byte_string('\0')
  12. def _std_string(s):
  13. """Cast a string or byte string to an ASCII string."""
  14. return str(s.decode('ASCII'))
  15. def build_tzinfo(zone, fp):
  16. head_fmt = '>4s c 15x 6l'
  17. head_size = calcsize(head_fmt)
  18. (magic, format, ttisgmtcnt, ttisstdcnt, leapcnt, timecnt,
  19. typecnt, charcnt) = unpack(head_fmt, fp.read(head_size))
  20. # Make sure it is a tzfile(5) file
  21. assert magic == _byte_string('TZif'), 'Got magic %s' % repr(magic)
  22. # Read out the transition times, localtime indices and ttinfo structures.
  23. data_fmt = '>%(timecnt)dl %(timecnt)dB %(ttinfo)s %(charcnt)ds' % dict(
  24. timecnt=timecnt, ttinfo='lBB' * typecnt, charcnt=charcnt)
  25. data_size = calcsize(data_fmt)
  26. data = unpack(data_fmt, fp.read(data_size))
  27. # make sure we unpacked the right number of values
  28. assert len(data) == 2 * timecnt + 3 * typecnt + 1
  29. transitions = [memorized_datetime(trans)
  30. for trans in data[:timecnt]]
  31. lindexes = list(data[timecnt:2 * timecnt])
  32. ttinfo_raw = data[2 * timecnt:-1]
  33. tznames_raw = data[-1]
  34. del data
  35. # Process ttinfo into separate structs
  36. ttinfo = []
  37. tznames = {}
  38. i = 0
  39. while i < len(ttinfo_raw):
  40. # have we looked up this timezone name yet?
  41. tzname_offset = ttinfo_raw[i + 2]
  42. if tzname_offset not in tznames:
  43. nul = tznames_raw.find(_NULL, tzname_offset)
  44. if nul < 0:
  45. nul = len(tznames_raw)
  46. tznames[tzname_offset] = _std_string(
  47. tznames_raw[tzname_offset:nul])
  48. ttinfo.append((ttinfo_raw[i],
  49. bool(ttinfo_raw[i + 1]),
  50. tznames[tzname_offset]))
  51. i += 3
  52. # Now build the timezone object
  53. if len(ttinfo) == 1 or len(transitions) == 0:
  54. ttinfo[0][0], ttinfo[0][2]
  55. cls = type(zone, (StaticTzInfo,), dict(
  56. zone=zone,
  57. _utcoffset=memorized_timedelta(ttinfo[0][0]),
  58. _tzname=ttinfo[0][2]))
  59. else:
  60. # Early dates use the first standard time ttinfo
  61. i = 0
  62. while ttinfo[i][1]:
  63. i += 1
  64. if ttinfo[i] == ttinfo[lindexes[0]]:
  65. transitions[0] = datetime.min
  66. else:
  67. transitions.insert(0, datetime.min)
  68. lindexes.insert(0, i)
  69. # calculate transition info
  70. transition_info = []
  71. for i in range(len(transitions)):
  72. inf = ttinfo[lindexes[i]]
  73. utcoffset = inf[0]
  74. if not inf[1]:
  75. dst = 0
  76. else:
  77. for j in range(i - 1, -1, -1):
  78. prev_inf = ttinfo[lindexes[j]]
  79. if not prev_inf[1]:
  80. break
  81. dst = inf[0] - prev_inf[0] # dst offset
  82. # Bad dst? Look further. DST > 24 hours happens when
  83. # a timzone has moved across the international dateline.
  84. if dst <= 0 or dst > 3600 * 3:
  85. for j in range(i + 1, len(transitions)):
  86. stdinf = ttinfo[lindexes[j]]
  87. if not stdinf[1]:
  88. dst = inf[0] - stdinf[0]
  89. if dst > 0:
  90. break # Found a useful std time.
  91. tzname = inf[2]
  92. # Round utcoffset and dst to the nearest minute or the
  93. # datetime library will complain. Conversions to these timezones
  94. # might be up to plus or minus 30 seconds out, but it is
  95. # the best we can do.
  96. utcoffset = int((utcoffset + 30) // 60) * 60
  97. dst = int((dst + 30) // 60) * 60
  98. transition_info.append(memorized_ttinfo(utcoffset, dst, tzname))
  99. cls = type(zone, (DstTzInfo,), dict(
  100. zone=zone,
  101. _utc_transition_times=transitions,
  102. _transition_info=transition_info))
  103. return cls()
  104. if __name__ == '__main__':
  105. import os.path
  106. from pprint import pprint
  107. base = os.path.join(os.path.dirname(__file__), 'zoneinfo')
  108. tz = build_tzinfo('Australia/Melbourne',
  109. open(os.path.join(base, 'Australia', 'Melbourne'), 'rb'))
  110. tz = build_tzinfo('US/Eastern',
  111. open(os.path.join(base, 'US', 'Eastern'), 'rb'))
  112. pprint(tz._utc_transition_times)