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 8.2KB

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