Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

timezone.py 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. """
  2. Timezone-related classes and functions.
  3. """
  4. import functools
  5. import sys
  6. import warnings
  7. try:
  8. import zoneinfo
  9. except ImportError:
  10. from backports import zoneinfo
  11. from contextlib import ContextDecorator
  12. from datetime import datetime, timedelta, timezone, tzinfo
  13. from asgiref.local import Local
  14. from django.conf import settings
  15. from django.utils.deprecation import RemovedInDjango50Warning
  16. __all__ = [ # noqa for utc RemovedInDjango50Warning.
  17. "utc",
  18. "get_fixed_timezone",
  19. "get_default_timezone",
  20. "get_default_timezone_name",
  21. "get_current_timezone",
  22. "get_current_timezone_name",
  23. "activate",
  24. "deactivate",
  25. "override",
  26. "localtime",
  27. "localdate",
  28. "now",
  29. "is_aware",
  30. "is_naive",
  31. "make_aware",
  32. "make_naive",
  33. ]
  34. # RemovedInDjango50Warning: sentinel for deprecation of is_dst parameters.
  35. NOT_PASSED = object()
  36. def __getattr__(name):
  37. if name != "utc":
  38. raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
  39. warnings.warn(
  40. "The django.utils.timezone.utc alias is deprecated. "
  41. "Please update your code to use datetime.timezone.utc instead.",
  42. RemovedInDjango50Warning,
  43. stacklevel=2,
  44. )
  45. return timezone.utc
  46. def get_fixed_timezone(offset):
  47. """Return a tzinfo instance with a fixed offset from UTC."""
  48. if isinstance(offset, timedelta):
  49. offset = offset.total_seconds() // 60
  50. sign = "-" if offset < 0 else "+"
  51. hhmm = "%02d%02d" % divmod(abs(offset), 60)
  52. name = sign + hhmm
  53. return timezone(timedelta(minutes=offset), name)
  54. # In order to avoid accessing settings at compile time,
  55. # wrap the logic in a function and cache the result.
  56. @functools.lru_cache
  57. def get_default_timezone():
  58. """
  59. Return the default time zone as a tzinfo instance.
  60. This is the time zone defined by settings.TIME_ZONE.
  61. """
  62. if settings.USE_DEPRECATED_PYTZ:
  63. import pytz
  64. return pytz.timezone(settings.TIME_ZONE)
  65. return zoneinfo.ZoneInfo(settings.TIME_ZONE)
  66. # This function exists for consistency with get_current_timezone_name
  67. def get_default_timezone_name():
  68. """Return the name of the default time zone."""
  69. return _get_timezone_name(get_default_timezone())
  70. _active = Local()
  71. def get_current_timezone():
  72. """Return the currently active time zone as a tzinfo instance."""
  73. return getattr(_active, "value", get_default_timezone())
  74. def get_current_timezone_name():
  75. """Return the name of the currently active time zone."""
  76. return _get_timezone_name(get_current_timezone())
  77. def _get_timezone_name(timezone):
  78. """
  79. Return the offset for fixed offset timezones, or the name of timezone if
  80. not set.
  81. """
  82. return timezone.tzname(None) or str(timezone)
  83. # Timezone selection functions.
  84. # These functions don't change os.environ['TZ'] and call time.tzset()
  85. # because it isn't thread safe.
  86. def activate(timezone):
  87. """
  88. Set the time zone for the current thread.
  89. The ``timezone`` argument must be an instance of a tzinfo subclass or a
  90. time zone name.
  91. """
  92. if isinstance(timezone, tzinfo):
  93. _active.value = timezone
  94. elif isinstance(timezone, str):
  95. if settings.USE_DEPRECATED_PYTZ:
  96. import pytz
  97. _active.value = pytz.timezone(timezone)
  98. else:
  99. _active.value = zoneinfo.ZoneInfo(timezone)
  100. else:
  101. raise ValueError("Invalid timezone: %r" % timezone)
  102. def deactivate():
  103. """
  104. Unset the time zone for the current thread.
  105. Django will then use the time zone defined by settings.TIME_ZONE.
  106. """
  107. if hasattr(_active, "value"):
  108. del _active.value
  109. class override(ContextDecorator):
  110. """
  111. Temporarily set the time zone for the current thread.
  112. This is a context manager that uses django.utils.timezone.activate()
  113. to set the timezone on entry and restores the previously active timezone
  114. on exit.
  115. The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
  116. time zone name, or ``None``. If it is ``None``, Django enables the default
  117. time zone.
  118. """
  119. def __init__(self, timezone):
  120. self.timezone = timezone
  121. def __enter__(self):
  122. self.old_timezone = getattr(_active, "value", None)
  123. if self.timezone is None:
  124. deactivate()
  125. else:
  126. activate(self.timezone)
  127. def __exit__(self, exc_type, exc_value, traceback):
  128. if self.old_timezone is None:
  129. deactivate()
  130. else:
  131. _active.value = self.old_timezone
  132. # Templates
  133. def template_localtime(value, use_tz=None):
  134. """
  135. Check if value is a datetime and converts it to local time if necessary.
  136. If use_tz is provided and is not None, that will force the value to
  137. be converted (or not), overriding the value of settings.USE_TZ.
  138. This function is designed for use by the template engine.
  139. """
  140. should_convert = (
  141. isinstance(value, datetime)
  142. and (settings.USE_TZ if use_tz is None else use_tz)
  143. and not is_naive(value)
  144. and getattr(value, "convert_to_local_time", True)
  145. )
  146. return localtime(value) if should_convert else value
  147. # Utilities
  148. def localtime(value=None, timezone=None):
  149. """
  150. Convert an aware datetime.datetime to local time.
  151. Only aware datetimes are allowed. When value is omitted, it defaults to
  152. now().
  153. Local time is defined by the current time zone, unless another time zone
  154. is specified.
  155. """
  156. if value is None:
  157. value = now()
  158. if timezone is None:
  159. timezone = get_current_timezone()
  160. # Emulate the behavior of astimezone() on Python < 3.6.
  161. if is_naive(value):
  162. raise ValueError("localtime() cannot be applied to a naive datetime")
  163. return value.astimezone(timezone)
  164. def localdate(value=None, timezone=None):
  165. """
  166. Convert an aware datetime to local time and return the value's date.
  167. Only aware datetimes are allowed. When value is omitted, it defaults to
  168. now().
  169. Local time is defined by the current time zone, unless another time zone is
  170. specified.
  171. """
  172. return localtime(value, timezone).date()
  173. def now():
  174. """
  175. Return an aware or naive datetime.datetime, depending on settings.USE_TZ.
  176. """
  177. return datetime.now(tz=timezone.utc if settings.USE_TZ else None)
  178. # By design, these four functions don't perform any checks on their arguments.
  179. # The caller should ensure that they don't receive an invalid value like None.
  180. def is_aware(value):
  181. """
  182. Determine if a given datetime.datetime is aware.
  183. The concept is defined in Python's docs:
  184. https://docs.python.org/library/datetime.html#datetime.tzinfo
  185. Assuming value.tzinfo is either None or a proper datetime.tzinfo,
  186. value.utcoffset() implements the appropriate logic.
  187. """
  188. return value.utcoffset() is not None
  189. def is_naive(value):
  190. """
  191. Determine if a given datetime.datetime is naive.
  192. The concept is defined in Python's docs:
  193. https://docs.python.org/library/datetime.html#datetime.tzinfo
  194. Assuming value.tzinfo is either None or a proper datetime.tzinfo,
  195. value.utcoffset() implements the appropriate logic.
  196. """
  197. return value.utcoffset() is None
  198. def make_aware(value, timezone=None, is_dst=NOT_PASSED):
  199. """Make a naive datetime.datetime in a given time zone aware."""
  200. if is_dst is NOT_PASSED:
  201. is_dst = None
  202. else:
  203. warnings.warn(
  204. "The is_dst argument to make_aware(), used by the Trunc() "
  205. "database functions and QuerySet.datetimes(), is deprecated as it "
  206. "has no effect with zoneinfo time zones.",
  207. RemovedInDjango50Warning,
  208. )
  209. if timezone is None:
  210. timezone = get_current_timezone()
  211. if _is_pytz_zone(timezone):
  212. # This method is available for pytz time zones.
  213. return timezone.localize(value, is_dst=is_dst)
  214. else:
  215. # Check that we won't overwrite the timezone of an aware datetime.
  216. if is_aware(value):
  217. raise ValueError("make_aware expects a naive datetime, got %s" % value)
  218. # This may be wrong around DST changes!
  219. return value.replace(tzinfo=timezone)
  220. def make_naive(value, timezone=None):
  221. """Make an aware datetime.datetime naive in a given time zone."""
  222. if timezone is None:
  223. timezone = get_current_timezone()
  224. # Emulate the behavior of astimezone() on Python < 3.6.
  225. if is_naive(value):
  226. raise ValueError("make_naive() cannot be applied to a naive datetime")
  227. return value.astimezone(timezone).replace(tzinfo=None)
  228. _PYTZ_IMPORTED = False
  229. def _pytz_imported():
  230. """
  231. Detects whether or not pytz has been imported without importing pytz.
  232. Copied from pytz_deprecation_shim with thanks to Paul Ganssle.
  233. """
  234. global _PYTZ_IMPORTED
  235. if not _PYTZ_IMPORTED and "pytz" in sys.modules:
  236. _PYTZ_IMPORTED = True
  237. return _PYTZ_IMPORTED
  238. def _is_pytz_zone(tz):
  239. """Checks if a zone is a pytz zone."""
  240. # See if pytz was already imported rather than checking
  241. # settings.USE_DEPRECATED_PYTZ to *allow* manually passing a pytz timezone,
  242. # which some of the test cases (at least) rely on.
  243. if not _pytz_imported():
  244. return False
  245. # If tz could be pytz, then pytz is needed here.
  246. import pytz
  247. _PYTZ_BASE_CLASSES = (pytz.tzinfo.BaseTzInfo, pytz._FixedOffset)
  248. # In releases prior to 2018.4, pytz.UTC was not a subclass of BaseTzInfo
  249. if not isinstance(pytz.UTC, pytz._FixedOffset):
  250. _PYTZ_BASE_CLASSES = _PYTZ_BASE_CLASSES + (type(pytz.UTC),)
  251. return isinstance(tz, _PYTZ_BASE_CLASSES)
  252. def _datetime_ambiguous_or_imaginary(dt, tz):
  253. if _is_pytz_zone(tz):
  254. import pytz
  255. try:
  256. tz.utcoffset(dt)
  257. except (pytz.AmbiguousTimeError, pytz.NonExistentTimeError):
  258. return True
  259. else:
  260. return False
  261. return tz.utcoffset(dt.replace(fold=not dt.fold)) != tz.utcoffset(dt)
  262. # RemovedInDjango50Warning.
  263. _DIR = dir()
  264. def __dir__():
  265. return sorted([*_DIR, "utc"])