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.
 
 
 
 

387 lines
11 KiB

  1. """
  2. Timezone-related classes and functions.
  3. This module uses pytz when it's available and fallbacks when it isn't.
  4. """
  5. import sys
  6. import time as _time
  7. from datetime import datetime, timedelta, tzinfo
  8. from threading import local
  9. from django.conf import settings
  10. from django.utils import lru_cache, six
  11. from django.utils.decorators import ContextDecorator
  12. try:
  13. import pytz
  14. except ImportError:
  15. pytz = None
  16. __all__ = [
  17. 'utc', 'get_fixed_timezone',
  18. 'get_default_timezone', 'get_default_timezone_name',
  19. 'get_current_timezone', 'get_current_timezone_name',
  20. 'activate', 'deactivate', 'override',
  21. 'localtime', 'now',
  22. 'is_aware', 'is_naive', 'make_aware', 'make_naive',
  23. ]
  24. # UTC and local time zones
  25. ZERO = timedelta(0)
  26. class UTC(tzinfo):
  27. """
  28. UTC implementation taken from Python's docs.
  29. Used only when pytz isn't available.
  30. """
  31. def __repr__(self):
  32. return "<UTC>"
  33. def utcoffset(self, dt):
  34. return ZERO
  35. def tzname(self, dt):
  36. return "UTC"
  37. def dst(self, dt):
  38. return ZERO
  39. class FixedOffset(tzinfo):
  40. """
  41. Fixed offset in minutes east from UTC. Taken from Python's docs.
  42. Kept as close as possible to the reference version. __init__ was changed
  43. to make its arguments optional, according to Python's requirement that
  44. tzinfo subclasses can be instantiated without arguments.
  45. """
  46. def __init__(self, offset=None, name=None):
  47. if offset is not None:
  48. self.__offset = timedelta(minutes=offset)
  49. if name is not None:
  50. self.__name = name
  51. def utcoffset(self, dt):
  52. return self.__offset
  53. def tzname(self, dt):
  54. return self.__name
  55. def dst(self, dt):
  56. return ZERO
  57. class ReferenceLocalTimezone(tzinfo):
  58. """
  59. Local time. Taken from Python's docs.
  60. Used only when pytz isn't available, and most likely inaccurate. If you're
  61. having trouble with this class, don't waste your time, just install pytz.
  62. Kept as close as possible to the reference version. __init__ was added to
  63. delay the computation of STDOFFSET, DSTOFFSET and DSTDIFF which is
  64. performed at import time in the example.
  65. Subclasses contain further improvements.
  66. """
  67. def __init__(self):
  68. self.STDOFFSET = timedelta(seconds=-_time.timezone)
  69. if _time.daylight:
  70. self.DSTOFFSET = timedelta(seconds=-_time.altzone)
  71. else:
  72. self.DSTOFFSET = self.STDOFFSET
  73. self.DSTDIFF = self.DSTOFFSET - self.STDOFFSET
  74. tzinfo.__init__(self)
  75. def utcoffset(self, dt):
  76. if self._isdst(dt):
  77. return self.DSTOFFSET
  78. else:
  79. return self.STDOFFSET
  80. def dst(self, dt):
  81. if self._isdst(dt):
  82. return self.DSTDIFF
  83. else:
  84. return ZERO
  85. def tzname(self, dt):
  86. return _time.tzname[self._isdst(dt)]
  87. def _isdst(self, dt):
  88. tt = (dt.year, dt.month, dt.day,
  89. dt.hour, dt.minute, dt.second,
  90. dt.weekday(), 0, 0)
  91. stamp = _time.mktime(tt)
  92. tt = _time.localtime(stamp)
  93. return tt.tm_isdst > 0
  94. class LocalTimezone(ReferenceLocalTimezone):
  95. """
  96. Slightly improved local time implementation focusing on correctness.
  97. It still crashes on dates before 1970 or after 2038, but at least the
  98. error message is helpful.
  99. """
  100. def tzname(self, dt):
  101. is_dst = False if dt is None else self._isdst(dt)
  102. return _time.tzname[is_dst]
  103. def _isdst(self, dt):
  104. try:
  105. return super(LocalTimezone, self)._isdst(dt)
  106. except (OverflowError, ValueError) as exc:
  107. exc_type = type(exc)
  108. exc_value = exc_type(
  109. "Unsupported value: %r. You should install pytz." % dt)
  110. exc_value.__cause__ = exc
  111. six.reraise(exc_type, exc_value, sys.exc_info()[2])
  112. utc = pytz.utc if pytz else UTC()
  113. """UTC time zone as a tzinfo instance."""
  114. def get_fixed_timezone(offset):
  115. """
  116. Returns a tzinfo instance with a fixed offset from UTC.
  117. """
  118. if isinstance(offset, timedelta):
  119. offset = offset.seconds // 60
  120. sign = '-' if offset < 0 else '+'
  121. hhmm = '%02d%02d' % divmod(abs(offset), 60)
  122. name = sign + hhmm
  123. return FixedOffset(offset, name)
  124. # In order to avoid accessing settings at compile time,
  125. # wrap the logic in a function and cache the result.
  126. @lru_cache.lru_cache()
  127. def get_default_timezone():
  128. """
  129. Returns the default time zone as a tzinfo instance.
  130. This is the time zone defined by settings.TIME_ZONE.
  131. """
  132. if isinstance(settings.TIME_ZONE, six.string_types) and pytz is not None:
  133. return pytz.timezone(settings.TIME_ZONE)
  134. else:
  135. # This relies on os.environ['TZ'] being set to settings.TIME_ZONE.
  136. return LocalTimezone()
  137. # This function exists for consistency with get_current_timezone_name
  138. def get_default_timezone_name():
  139. """
  140. Returns the name of the default time zone.
  141. """
  142. return _get_timezone_name(get_default_timezone())
  143. _active = local()
  144. def get_current_timezone():
  145. """
  146. Returns the currently active time zone as a tzinfo instance.
  147. """
  148. return getattr(_active, "value", get_default_timezone())
  149. def get_current_timezone_name():
  150. """
  151. Returns the name of the currently active time zone.
  152. """
  153. return _get_timezone_name(get_current_timezone())
  154. def _get_timezone_name(timezone):
  155. """
  156. Returns the name of ``timezone``.
  157. """
  158. try:
  159. # for pytz timezones
  160. return timezone.zone
  161. except AttributeError:
  162. # for regular tzinfo objects
  163. return timezone.tzname(None)
  164. # Timezone selection functions.
  165. # These functions don't change os.environ['TZ'] and call time.tzset()
  166. # because it isn't thread safe.
  167. def activate(timezone):
  168. """
  169. Sets the time zone for the current thread.
  170. The ``timezone`` argument must be an instance of a tzinfo subclass or a
  171. time zone name. If it is a time zone name, pytz is required.
  172. """
  173. if isinstance(timezone, tzinfo):
  174. _active.value = timezone
  175. elif isinstance(timezone, six.string_types) and pytz is not None:
  176. _active.value = pytz.timezone(timezone)
  177. else:
  178. raise ValueError("Invalid timezone: %r" % timezone)
  179. def deactivate():
  180. """
  181. Unsets the time zone for the current thread.
  182. Django will then use the time zone defined by settings.TIME_ZONE.
  183. """
  184. if hasattr(_active, "value"):
  185. del _active.value
  186. class override(ContextDecorator):
  187. """
  188. Temporarily set the time zone for the current thread.
  189. This is a context manager that uses ``~django.utils.timezone.activate()``
  190. to set the timezone on entry, and restores the previously active timezone
  191. on exit.
  192. The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
  193. time zone name, or ``None``. If is it a time zone name, pytz is required.
  194. If it is ``None``, Django enables the default time zone.
  195. """
  196. def __init__(self, timezone):
  197. self.timezone = timezone
  198. def __enter__(self):
  199. self.old_timezone = getattr(_active, 'value', None)
  200. if self.timezone is None:
  201. deactivate()
  202. else:
  203. activate(self.timezone)
  204. def __exit__(self, exc_type, exc_value, traceback):
  205. if self.old_timezone is None:
  206. deactivate()
  207. else:
  208. _active.value = self.old_timezone
  209. # Templates
  210. def template_localtime(value, use_tz=None):
  211. """
  212. Checks if value is a datetime and converts it to local time if necessary.
  213. If use_tz is provided and is not None, that will force the value to
  214. be converted (or not), overriding the value of settings.USE_TZ.
  215. This function is designed for use by the template engine.
  216. """
  217. should_convert = (isinstance(value, datetime)
  218. and (settings.USE_TZ if use_tz is None else use_tz)
  219. and not is_naive(value)
  220. and getattr(value, 'convert_to_local_time', True))
  221. return localtime(value) if should_convert else value
  222. # Utilities
  223. def localtime(value, timezone=None):
  224. """
  225. Converts an aware datetime.datetime to local time.
  226. Local time is defined by the current time zone, unless another time zone
  227. is specified.
  228. """
  229. if timezone is None:
  230. timezone = get_current_timezone()
  231. # If `value` is naive, astimezone() will raise a ValueError,
  232. # so we don't need to perform a redundant check.
  233. value = value.astimezone(timezone)
  234. if hasattr(timezone, 'normalize'):
  235. # This method is available for pytz time zones.
  236. value = timezone.normalize(value)
  237. return value
  238. def now():
  239. """
  240. Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
  241. """
  242. if settings.USE_TZ:
  243. # timeit shows that datetime.now(tz=utc) is 24% slower
  244. return datetime.utcnow().replace(tzinfo=utc)
  245. else:
  246. return datetime.now()
  247. # By design, these four functions don't perform any checks on their arguments.
  248. # The caller should ensure that they don't receive an invalid value like None.
  249. def is_aware(value):
  250. """
  251. Determines if a given datetime.datetime is aware.
  252. The concept is defined in Python's docs:
  253. http://docs.python.org/library/datetime.html#datetime.tzinfo
  254. Assuming value.tzinfo is either None or a proper datetime.tzinfo,
  255. value.utcoffset() implements the appropriate logic.
  256. """
  257. return value.utcoffset() is not None
  258. def is_naive(value):
  259. """
  260. Determines if a given datetime.datetime is naive.
  261. The concept is defined in Python's docs:
  262. http://docs.python.org/library/datetime.html#datetime.tzinfo
  263. Assuming value.tzinfo is either None or a proper datetime.tzinfo,
  264. value.utcoffset() implements the appropriate logic.
  265. """
  266. return value.utcoffset() is None
  267. def make_aware(value, timezone=None, is_dst=None):
  268. """
  269. Makes a naive datetime.datetime in a given time zone aware.
  270. """
  271. if timezone is None:
  272. timezone = get_current_timezone()
  273. if hasattr(timezone, 'localize'):
  274. # This method is available for pytz time zones.
  275. return timezone.localize(value, is_dst=is_dst)
  276. else:
  277. # Check that we won't overwrite the timezone of an aware datetime.
  278. if is_aware(value):
  279. raise ValueError(
  280. "make_aware expects a naive datetime, got %s" % value)
  281. # This may be wrong around DST changes!
  282. return value.replace(tzinfo=timezone)
  283. def make_naive(value, timezone=None):
  284. """
  285. Makes an aware datetime.datetime naive in a given time zone.
  286. """
  287. if timezone is None:
  288. timezone = get_current_timezone()
  289. # If `value` is naive, astimezone() will raise a ValueError,
  290. # so we don't need to perform a redundant check.
  291. value = value.astimezone(timezone)
  292. if hasattr(timezone, 'normalize'):
  293. # This method is available for pytz time zones.
  294. value = timezone.normalize(value)
  295. return value.replace(tzinfo=None)