timezone.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. """
  2. Timezone-related classes and functions.
  3. """
  4. import functools
  5. from contextlib import ContextDecorator
  6. from datetime import datetime, timedelta, timezone, tzinfo
  7. import pytz
  8. from asgiref.local import Local
  9. from django.conf import settings
  10. __all__ = [
  11. 'utc', 'get_fixed_timezone',
  12. 'get_default_timezone', 'get_default_timezone_name',
  13. 'get_current_timezone', 'get_current_timezone_name',
  14. 'activate', 'deactivate', 'override',
  15. 'localtime', 'now',
  16. 'is_aware', 'is_naive', 'make_aware', 'make_naive',
  17. ]
  18. # UTC time zone as a tzinfo instance.
  19. utc = pytz.utc
  20. _PYTZ_BASE_CLASSES = (pytz.tzinfo.BaseTzInfo, pytz._FixedOffset)
  21. # In releases prior to 2018.4, pytz.UTC was not a subclass of BaseTzInfo
  22. if not isinstance(pytz.UTC, pytz._FixedOffset):
  23. _PYTZ_BASE_CLASSES = _PYTZ_BASE_CLASSES + (type(pytz.UTC),)
  24. def get_fixed_timezone(offset):
  25. """Return a tzinfo instance with a fixed offset from UTC."""
  26. if isinstance(offset, timedelta):
  27. offset = offset.total_seconds() // 60
  28. sign = '-' if offset < 0 else '+'
  29. hhmm = '%02d%02d' % divmod(abs(offset), 60)
  30. name = sign + hhmm
  31. return timezone(timedelta(minutes=offset), name)
  32. # In order to avoid accessing settings at compile time,
  33. # wrap the logic in a function and cache the result.
  34. @functools.lru_cache()
  35. def get_default_timezone():
  36. """
  37. Return the default time zone as a tzinfo instance.
  38. This is the time zone defined by settings.TIME_ZONE.
  39. """
  40. return pytz.timezone(settings.TIME_ZONE)
  41. # This function exists for consistency with get_current_timezone_name
  42. def get_default_timezone_name():
  43. """Return the name of the default time zone."""
  44. return _get_timezone_name(get_default_timezone())
  45. _active = Local()
  46. def get_current_timezone():
  47. """Return the currently active time zone as a tzinfo instance."""
  48. return getattr(_active, "value", get_default_timezone())
  49. def get_current_timezone_name():
  50. """Return the name of the currently active time zone."""
  51. return _get_timezone_name(get_current_timezone())
  52. def _get_timezone_name(timezone):
  53. """
  54. Return the offset for fixed offset timezones, or the name of timezone if
  55. not set.
  56. """
  57. return timezone.tzname(None) or str(timezone)
  58. # Timezone selection functions.
  59. # These functions don't change os.environ['TZ'] and call time.tzset()
  60. # because it isn't thread safe.
  61. def activate(timezone):
  62. """
  63. Set the time zone for the current thread.
  64. The ``timezone`` argument must be an instance of a tzinfo subclass or a
  65. time zone name.
  66. """
  67. if isinstance(timezone, tzinfo):
  68. _active.value = timezone
  69. elif isinstance(timezone, str):
  70. _active.value = pytz.timezone(timezone)
  71. else:
  72. raise ValueError("Invalid timezone: %r" % timezone)
  73. def deactivate():
  74. """
  75. Unset the time zone for the current thread.
  76. Django will then use the time zone defined by settings.TIME_ZONE.
  77. """
  78. if hasattr(_active, "value"):
  79. del _active.value
  80. class override(ContextDecorator):
  81. """
  82. Temporarily set the time zone for the current thread.
  83. This is a context manager that uses django.utils.timezone.activate()
  84. to set the timezone on entry and restores the previously active timezone
  85. on exit.
  86. The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
  87. time zone name, or ``None``. If it is ``None``, Django enables the default
  88. time zone.
  89. """
  90. def __init__(self, timezone):
  91. self.timezone = timezone
  92. def __enter__(self):
  93. self.old_timezone = getattr(_active, 'value', None)
  94. if self.timezone is None:
  95. deactivate()
  96. else:
  97. activate(self.timezone)
  98. def __exit__(self, exc_type, exc_value, traceback):
  99. if self.old_timezone is None:
  100. deactivate()
  101. else:
  102. _active.value = self.old_timezone
  103. # Templates
  104. def template_localtime(value, use_tz=None):
  105. """
  106. Check if value is a datetime and converts it to local time if necessary.
  107. If use_tz is provided and is not None, that will force the value to
  108. be converted (or not), overriding the value of settings.USE_TZ.
  109. This function is designed for use by the template engine.
  110. """
  111. should_convert = (
  112. isinstance(value, datetime) and
  113. (settings.USE_TZ if use_tz is None else use_tz) and
  114. not is_naive(value) and
  115. getattr(value, 'convert_to_local_time', True)
  116. )
  117. return localtime(value) if should_convert else value
  118. # Utilities
  119. def localtime(value=None, timezone=None):
  120. """
  121. Convert an aware datetime.datetime to local time.
  122. Only aware datetimes are allowed. When value is omitted, it defaults to
  123. now().
  124. Local time is defined by the current time zone, unless another time zone
  125. is specified.
  126. """
  127. if value is None:
  128. value = now()
  129. if timezone is None:
  130. timezone = get_current_timezone()
  131. # Emulate the behavior of astimezone() on Python < 3.6.
  132. if is_naive(value):
  133. raise ValueError("localtime() cannot be applied to a naive datetime")
  134. return value.astimezone(timezone)
  135. def localdate(value=None, timezone=None):
  136. """
  137. Convert an aware datetime to local time and return the value's date.
  138. Only aware datetimes are allowed. When value is omitted, it defaults to
  139. now().
  140. Local time is defined by the current time zone, unless another time zone is
  141. specified.
  142. """
  143. return localtime(value, timezone).date()
  144. def now():
  145. """
  146. Return an aware or naive datetime.datetime, depending on settings.USE_TZ.
  147. """
  148. if settings.USE_TZ:
  149. # timeit shows that datetime.now(tz=utc) is 24% slower
  150. return datetime.utcnow().replace(tzinfo=utc)
  151. else:
  152. return datetime.now()
  153. # By design, these four functions don't perform any checks on their arguments.
  154. # The caller should ensure that they don't receive an invalid value like None.
  155. def is_aware(value):
  156. """
  157. Determine if a given datetime.datetime is aware.
  158. The concept is defined in Python's docs:
  159. https://docs.python.org/library/datetime.html#datetime.tzinfo
  160. Assuming value.tzinfo is either None or a proper datetime.tzinfo,
  161. value.utcoffset() implements the appropriate logic.
  162. """
  163. return value.utcoffset() is not None
  164. def is_naive(value):
  165. """
  166. Determine if a given datetime.datetime is naive.
  167. The concept is defined in Python's docs:
  168. https://docs.python.org/library/datetime.html#datetime.tzinfo
  169. Assuming value.tzinfo is either None or a proper datetime.tzinfo,
  170. value.utcoffset() implements the appropriate logic.
  171. """
  172. return value.utcoffset() is None
  173. def make_aware(value, timezone=None, is_dst=None):
  174. """Make a naive datetime.datetime in a given time zone aware."""
  175. if timezone is None:
  176. timezone = get_current_timezone()
  177. if _is_pytz_zone(timezone):
  178. # This method is available for pytz time zones.
  179. return timezone.localize(value, is_dst=is_dst)
  180. else:
  181. # Check that we won't overwrite the timezone of an aware datetime.
  182. if is_aware(value):
  183. raise ValueError(
  184. "make_aware expects a naive datetime, got %s" % value)
  185. # This may be wrong around DST changes!
  186. return value.replace(tzinfo=timezone)
  187. def make_naive(value, timezone=None):
  188. """Make an aware datetime.datetime naive in a given time zone."""
  189. if timezone is None:
  190. timezone = get_current_timezone()
  191. # Emulate the behavior of astimezone() on Python < 3.6.
  192. if is_naive(value):
  193. raise ValueError("make_naive() cannot be applied to a naive datetime")
  194. return value.astimezone(timezone).replace(tzinfo=None)
  195. def _is_pytz_zone(tz):
  196. """Checks if a zone is a pytz zone."""
  197. return isinstance(tz, _PYTZ_BASE_CLASSES)
  198. def _datetime_ambiguous_or_imaginary(dt, tz):
  199. if _is_pytz_zone(tz):
  200. try:
  201. tz.utcoffset(dt)
  202. except (pytz.AmbiguousTimeError, pytz.NonExistentTimeError):
  203. return True
  204. else:
  205. return False
  206. return tz.utcoffset(dt.replace(fold=not dt.fold)) != tz.utcoffset(dt)