__init__.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. """
  3. babel.localtime
  4. ~~~~~~~~~~~~~~~
  5. Babel specific fork of tzlocal to determine the local timezone
  6. of the system.
  7. :copyright: (c) 2013-2021 by the Babel Team.
  8. :license: BSD, see LICENSE for more details.
  9. """
  10. import sys
  11. import pytz
  12. import time
  13. from datetime import timedelta
  14. from datetime import tzinfo
  15. from threading import RLock
  16. if sys.platform == 'win32':
  17. from babel.localtime._win32 import _get_localzone
  18. else:
  19. from babel.localtime._unix import _get_localzone
  20. _cached_tz = None
  21. _cache_lock = RLock()
  22. STDOFFSET = timedelta(seconds=-time.timezone)
  23. if time.daylight:
  24. DSTOFFSET = timedelta(seconds=-time.altzone)
  25. else:
  26. DSTOFFSET = STDOFFSET
  27. DSTDIFF = DSTOFFSET - STDOFFSET
  28. ZERO = timedelta(0)
  29. class _FallbackLocalTimezone(tzinfo):
  30. def utcoffset(self, dt):
  31. if self._isdst(dt):
  32. return DSTOFFSET
  33. else:
  34. return STDOFFSET
  35. def dst(self, dt):
  36. if self._isdst(dt):
  37. return DSTDIFF
  38. else:
  39. return ZERO
  40. def tzname(self, dt):
  41. return time.tzname[self._isdst(dt)]
  42. def _isdst(self, dt):
  43. tt = (dt.year, dt.month, dt.day,
  44. dt.hour, dt.minute, dt.second,
  45. dt.weekday(), 0, -1)
  46. stamp = time.mktime(tt)
  47. tt = time.localtime(stamp)
  48. return tt.tm_isdst > 0
  49. def get_localzone():
  50. """Returns the current underlying local timezone object.
  51. Generally this function does not need to be used, it's a
  52. better idea to use the :data:`LOCALTZ` singleton instead.
  53. """
  54. return _get_localzone()
  55. try:
  56. LOCALTZ = get_localzone()
  57. except pytz.UnknownTimeZoneError:
  58. LOCALTZ = _FallbackLocalTimezone()