Development of an internal social media platform with personalised dashboards for students
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 7.9KB

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