timezone.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. """
  2. Timezone-related classes and functions.
  3. This module uses pytz when it's available and fallbacks when it isn't.
  4. """
  5. from datetime import datetime, timedelta, tzinfo
  6. from threading import local
  7. import sys
  8. import time as _time
  9. try:
  10. import pytz
  11. except ImportError:
  12. pytz = None
  13. from django.conf import settings
  14. from django.utils import six
  15. __all__ = [
  16. 'utc', 'get_fixed_timezone',
  17. 'get_default_timezone', 'get_default_timezone_name',
  18. 'get_current_timezone', 'get_current_timezone_name',
  19. 'activate', 'deactivate', 'override',
  20. 'localtime', 'now',
  21. 'is_aware', 'is_naive', 'make_aware', 'make_naive',
  22. ]
  23. # UTC and local time zones
  24. ZERO = timedelta(0)
  25. class UTC(tzinfo):
  26. """
  27. UTC implementation taken from Python's docs.
  28. Used only when pytz isn't available.
  29. """
  30. def __repr__(self):
  31. return "<UTC>"
  32. def utcoffset(self, dt):
  33. return ZERO
  34. def tzname(self, dt):
  35. return "UTC"
  36. def dst(self, dt):
  37. return ZERO
  38. class FixedOffset(tzinfo):
  39. """
  40. Fixed offset in minutes east from UTC. Taken from Python's docs.
  41. Kept as close as possible to the reference version. __init__ was changed
  42. to make its arguments optional, according to Python's requirement that
  43. tzinfo subclasses can be instantiated without arguments.
  44. """
  45. def __init__(self, offset=None, name=None):
  46. if offset is not None:
  47. self.__offset = timedelta(minutes=offset)
  48. if name is not None:
  49. self.__name = name
  50. def utcoffset(self, dt):
  51. return self.__offset
  52. def tzname(self, dt):
  53. return self.__name
  54. def dst(self, dt):
  55. return ZERO
  56. class ReferenceLocalTimezone(tzinfo):
  57. """
  58. Local time. Taken from Python's docs.
  59. Used only when pytz isn't available, and most likely inaccurate. If you're
  60. having trouble with this class, don't waste your time, just install pytz.
  61. Kept as close as possible to the reference version. __init__ was added to
  62. delay the computation of STDOFFSET, DSTOFFSET and DSTDIFF which is
  63. performed at import time in the example.
  64. Subclasses contain further improvements.
  65. """
  66. def __init__(self):
  67. self.STDOFFSET = timedelta(seconds=-_time.timezone)
  68. if _time.daylight:
  69. self.DSTOFFSET = timedelta(seconds=-_time.altzone)
  70. else:
  71. self.DSTOFFSET = self.STDOFFSET
  72. self.DSTDIFF = self.DSTOFFSET - self.STDOFFSET
  73. tzinfo.__init__(self)
  74. def utcoffset(self, dt):
  75. if self._isdst(dt):
  76. return self.DSTOFFSET
  77. else:
  78. return self.STDOFFSET
  79. def dst(self, dt):
  80. if self._isdst(dt):
  81. return self.DSTDIFF
  82. else:
  83. return ZERO
  84. def tzname(self, dt):
  85. return _time.tzname[self._isdst(dt)]
  86. def _isdst(self, dt):
  87. tt = (dt.year, dt.month, dt.day,
  88. dt.hour, dt.minute, dt.second,
  89. dt.weekday(), 0, 0)
  90. stamp = _time.mktime(tt)
  91. tt = _time.localtime(stamp)
  92. return tt.tm_isdst > 0
  93. class LocalTimezone(ReferenceLocalTimezone):
  94. """
  95. Slightly improved local time implementation focusing on correctness.
  96. It still crashes on dates before 1970 or after 2038, but at least the
  97. error message is helpful.
  98. """
  99. def tzname(self, dt):
  100. is_dst = False if dt is None else self._isdst(dt)
  101. return _time.tzname[is_dst]
  102. def _isdst(self, dt):
  103. try:
  104. return super(LocalTimezone, self)._isdst(dt)
  105. except (OverflowError, ValueError) as exc:
  106. exc_type = type(exc)
  107. exc_value = exc_type(
  108. "Unsupported value: %r. You should install pytz." % dt)
  109. exc_value.__cause__ = exc
  110. six.reraise(exc_type, exc_value, sys.exc_info()[2])
  111. utc = pytz.utc if pytz else UTC()
  112. """UTC time zone as a tzinfo instance."""
  113. def get_fixed_timezone(offset):
  114. """
  115. Returns a tzinfo instance with a fixed offset from UTC.
  116. """
  117. if isinstance(offset, timedelta):
  118. offset = offset.seconds // 60
  119. sign = '-' if offset < 0 else '+'
  120. hhmm = '%02d%02d' % divmod(abs(offset), 60)
  121. name = sign + hhmm
  122. return FixedOffset(offset, name)
  123. # In order to avoid accessing the settings at compile time,
  124. # wrap the expression in a function and cache the result.
  125. _localtime = None
  126. def get_default_timezone():
  127. """
  128. Returns the default time zone as a tzinfo instance.
  129. This is the time zone defined by settings.TIME_ZONE.
  130. """
  131. global _localtime
  132. if _localtime is None:
  133. if isinstance(settings.TIME_ZONE, six.string_types) and pytz is not None:
  134. _localtime = pytz.timezone(settings.TIME_ZONE)
  135. else:
  136. # This relies on os.environ['TZ'] being set to settings.TIME_ZONE.
  137. _localtime = LocalTimezone()
  138. return _localtime
  139. # This function exists for consistency with get_current_timezone_name
  140. def get_default_timezone_name():
  141. """
  142. Returns the name of the default time zone.
  143. """
  144. return _get_timezone_name(get_default_timezone())
  145. _active = local()
  146. def get_current_timezone():
  147. """
  148. Returns the currently active time zone as a tzinfo instance.
  149. """
  150. return getattr(_active, "value", get_default_timezone())
  151. def get_current_timezone_name():
  152. """
  153. Returns the name of the currently active time zone.
  154. """
  155. return _get_timezone_name(get_current_timezone())
  156. def _get_timezone_name(timezone):
  157. """
  158. Returns the name of ``timezone``.
  159. """
  160. try:
  161. # for pytz timezones
  162. return timezone.zone
  163. except AttributeError:
  164. # for regular tzinfo objects
  165. return timezone.tzname(None)
  166. # Timezone selection functions.
  167. # These functions don't change os.environ['TZ'] and call time.tzset()
  168. # because it isn't thread safe.
  169. def activate(timezone):
  170. """
  171. Sets the time zone for the current thread.
  172. The ``timezone`` argument must be an instance of a tzinfo subclass or a
  173. time zone name. If it is a time zone name, pytz is required.
  174. """
  175. if isinstance(timezone, tzinfo):
  176. _active.value = timezone
  177. elif isinstance(timezone, six.string_types) and pytz is not None:
  178. _active.value = pytz.timezone(timezone)
  179. else:
  180. raise ValueError("Invalid timezone: %r" % timezone)
  181. def deactivate():
  182. """
  183. Unsets the time zone for the current thread.
  184. Django will then use the time zone defined by settings.TIME_ZONE.
  185. """
  186. if hasattr(_active, "value"):
  187. del _active.value
  188. class override(object):
  189. """
  190. Temporarily set the time zone for the current thread.
  191. This is a context manager that uses ``~django.utils.timezone.activate()``
  192. to set the timezone on entry, and restores the previously active timezone
  193. on exit.
  194. The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
  195. time zone name, or ``None``. If is it a time zone name, pytz is required.
  196. If it is ``None``, Django enables the default time zone.
  197. """
  198. def __init__(self, timezone):
  199. self.timezone = timezone
  200. self.old_timezone = getattr(_active, 'value', None)
  201. def __enter__(self):
  202. if self.timezone is None:
  203. deactivate()
  204. else:
  205. activate(self.timezone)
  206. def __exit__(self, exc_type, exc_value, traceback):
  207. if self.old_timezone is None:
  208. deactivate()
  209. else:
  210. _active.value = self.old_timezone
  211. # Templates
  212. def template_localtime(value, use_tz=None):
  213. """
  214. Checks if value is a datetime and converts it to local time if necessary.
  215. If use_tz is provided and is not None, that will force the value to
  216. be converted (or not), overriding the value of settings.USE_TZ.
  217. This function is designed for use by the template engine.
  218. """
  219. should_convert = (isinstance(value, datetime)
  220. and (settings.USE_TZ if use_tz is None else use_tz)
  221. and not is_naive(value)
  222. and getattr(value, 'convert_to_local_time', True))
  223. return localtime(value) if should_convert else value
  224. # Utilities
  225. def localtime(value, timezone=None):
  226. """
  227. Converts an aware datetime.datetime to local time.
  228. Local time is defined by the current time zone, unless another time zone
  229. is specified.
  230. """
  231. if timezone is None:
  232. timezone = get_current_timezone()
  233. # If `value` is naive, astimezone() will raise a ValueError,
  234. # so we don't need to perform a redundant check.
  235. value = value.astimezone(timezone)
  236. if hasattr(timezone, 'normalize'):
  237. # This method is available for pytz time zones.
  238. value = timezone.normalize(value)
  239. return value
  240. def now():
  241. """
  242. Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
  243. """
  244. if settings.USE_TZ:
  245. # timeit shows that datetime.now(tz=utc) is 24% slower
  246. return datetime.utcnow().replace(tzinfo=utc)
  247. else:
  248. return datetime.now()
  249. # By design, these four functions don't perform any checks on their arguments.
  250. # The caller should ensure that they don't receive an invalid value like None.
  251. def is_aware(value):
  252. """
  253. Determines if a given datetime.datetime is aware.
  254. The logic is described in Python's docs:
  255. http://docs.python.org/library/datetime.html#datetime.tzinfo
  256. """
  257. return value.tzinfo is not None and value.tzinfo.utcoffset(value) is not None
  258. def is_naive(value):
  259. """
  260. Determines if a given datetime.datetime is naive.
  261. The logic is described in Python's docs:
  262. http://docs.python.org/library/datetime.html#datetime.tzinfo
  263. """
  264. return value.tzinfo is None or value.tzinfo.utcoffset(value) is None
  265. def make_aware(value, timezone):
  266. """
  267. Makes a naive datetime.datetime in a given time zone aware.
  268. """
  269. if hasattr(timezone, 'localize'):
  270. # This method is available for pytz time zones.
  271. return timezone.localize(value, is_dst=None)
  272. else:
  273. # Check that we won't overwrite the timezone of an aware datetime.
  274. if is_aware(value):
  275. raise ValueError(
  276. "make_aware expects a naive datetime, got %s" % value)
  277. # This may be wrong around DST changes!
  278. return value.replace(tzinfo=timezone)
  279. def make_naive(value, timezone):
  280. """
  281. Makes an aware datetime.datetime naive in a given time zone.
  282. """
  283. # If `value` is naive, astimezone() will raise a ValueError,
  284. # so we don't need to perform a redundant check.
  285. value = value.astimezone(timezone)
  286. if hasattr(timezone, 'normalize'):
  287. # This method is available for pytz time zones.
  288. value = timezone.normalize(value)
  289. return value.replace(tzinfo=None)