PageRenderTime 28ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/dateutil/zoneinfo/__init__.py

http://django-geo.googlecode.com/
Python | 87 lines | 71 code | 10 blank | 6 comment | 19 complexity | afb4c02dda896c31e32b6c61ae60d02c MD5 | raw file
  1. """
  2. Copyright (c) 2003-2005 Gustavo Niemeyer <gustavo@niemeyer.net>
  3. This module offers extensions to the standard python 2.3+
  4. datetime module.
  5. """
  6. from dateutil.tz import tzfile
  7. from tarfile import TarFile
  8. import os
  9. __author__ = "Gustavo Niemeyer <gustavo@niemeyer.net>"
  10. __license__ = "PSF License"
  11. __all__ = ["setcachesize", "gettz", "rebuild"]
  12. CACHE = []
  13. CACHESIZE = 10
  14. class tzfile(tzfile):
  15. def __reduce__(self):
  16. return (gettz, (self._filename,))
  17. def getzoneinfofile():
  18. filenames = os.listdir(os.path.join(os.path.dirname(__file__)))
  19. filenames.sort()
  20. filenames.reverse()
  21. for entry in filenames:
  22. if entry.startswith("zoneinfo") and ".tar." in entry:
  23. return os.path.join(os.path.dirname(__file__), entry)
  24. return None
  25. ZONEINFOFILE = getzoneinfofile()
  26. del getzoneinfofile
  27. def setcachesize(size):
  28. global CACHESIZE, CACHE
  29. CACHESIZE = size
  30. del CACHE[size:]
  31. def gettz(name):
  32. tzinfo = None
  33. if ZONEINFOFILE:
  34. for cachedname, tzinfo in CACHE:
  35. if cachedname == name:
  36. break
  37. else:
  38. tf = TarFile.open(ZONEINFOFILE)
  39. try:
  40. zonefile = tf.extractfile(name)
  41. except KeyError:
  42. tzinfo = None
  43. else:
  44. tzinfo = tzfile(zonefile)
  45. tf.close()
  46. CACHE.insert(0, (name, tzinfo))
  47. del CACHE[CACHESIZE:]
  48. return tzinfo
  49. def rebuild(filename, tag=None, format="gz"):
  50. import tempfile, shutil
  51. tmpdir = tempfile.mkdtemp()
  52. zonedir = os.path.join(tmpdir, "zoneinfo")
  53. moduledir = os.path.dirname(__file__)
  54. if tag: tag = "-"+tag
  55. targetname = "zoneinfo%s.tar.%s" % (tag, format)
  56. try:
  57. tf = TarFile.open(filename)
  58. for name in tf.getnames():
  59. if not (name.endswith(".sh") or
  60. name.endswith(".tab") or
  61. name == "leapseconds"):
  62. tf.extract(name, tmpdir)
  63. filepath = os.path.join(tmpdir, name)
  64. os.system("zic -d %s %s" % (zonedir, filepath))
  65. tf.close()
  66. target = os.path.join(moduledir, targetname)
  67. for entry in os.listdir(moduledir):
  68. if entry.startswith("zoneinfo") and ".tar." in entry:
  69. os.unlink(os.path.join(moduledir, entry))
  70. tf = TarFile.open(target, "w:%s" % format)
  71. for entry in os.listdir(zonedir):
  72. entrypath = os.path.join(zonedir, entry)
  73. tf.add(entrypath, entry)
  74. tf.close()
  75. finally:
  76. shutil.rmtree(tmpdir)