timezone.py 7.1 KB

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