2013-09-08 07:56:49 +08:00
|
|
|
"""
|
|
|
|
Timezone-related classes and functions.
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
|
|
|
|
2017-01-19 04:30:21 +08:00
|
|
|
import functools
|
2018-07-10 04:33:36 +08:00
|
|
|
import warnings
|
2017-01-20 00:28:30 +08:00
|
|
|
from contextlib import ContextDecorator
|
2018-07-10 04:33:36 +08:00
|
|
|
from datetime import datetime, timedelta, timezone, tzinfo
|
2015-01-28 20:35:27 +08:00
|
|
|
|
2016-10-08 09:06:49 +08:00
|
|
|
import pytz
|
2019-04-12 21:15:18 +08:00
|
|
|
from asgiref.local import Local
|
2016-10-08 09:06:49 +08:00
|
|
|
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.conf import settings
|
2018-07-10 04:33:36 +08:00
|
|
|
from django.utils.deprecation import RemovedInDjango31Warning
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
__all__ = [
|
2013-09-08 15:04:31 +08:00
|
|
|
'utc', 'get_fixed_timezone',
|
2014-01-26 22:35:22 +08:00
|
|
|
'get_default_timezone', 'get_default_timezone_name',
|
|
|
|
'get_current_timezone', 'get_current_timezone_name',
|
2011-11-18 21:01:06 +08:00
|
|
|
'activate', 'deactivate', 'override',
|
2014-01-26 22:35:22 +08:00
|
|
|
'localtime', 'now',
|
|
|
|
'is_aware', 'is_naive', 'make_aware', 'make_naive',
|
2011-11-18 21:01:06 +08:00
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
# UTC and local time zones
|
|
|
|
|
|
|
|
ZERO = timedelta(0)
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2013-09-08 15:04:31 +08:00
|
|
|
class FixedOffset(tzinfo):
|
|
|
|
"""
|
|
|
|
Fixed offset in minutes east from UTC. Taken from Python's docs.
|
|
|
|
|
|
|
|
Kept as close as possible to the reference version. __init__ was changed
|
|
|
|
to make its arguments optional, according to Python's requirement that
|
|
|
|
tzinfo subclasses can be instantiated without arguments.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, offset=None, name=None):
|
2018-07-10 04:33:36 +08:00
|
|
|
warnings.warn(
|
|
|
|
'FixedOffset is deprecated in favor of datetime.timezone',
|
|
|
|
RemovedInDjango31Warning, stacklevel=2,
|
|
|
|
)
|
2013-09-08 15:04:31 +08:00
|
|
|
if offset is not None:
|
|
|
|
self.__offset = timedelta(minutes=offset)
|
|
|
|
if name is not None:
|
|
|
|
self.__name = name
|
|
|
|
|
|
|
|
def utcoffset(self, dt):
|
|
|
|
return self.__offset
|
|
|
|
|
|
|
|
def tzname(self, dt):
|
|
|
|
return self.__name
|
|
|
|
|
|
|
|
def dst(self, dt):
|
|
|
|
return ZERO
|
|
|
|
|
2016-11-13 01:11:23 +08:00
|
|
|
|
2017-01-25 04:32:33 +08:00
|
|
|
# UTC time zone as a tzinfo instance.
|
2018-06-28 21:26:41 +08:00
|
|
|
utc = pytz.utc
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2013-09-08 15:04:31 +08:00
|
|
|
def get_fixed_timezone(offset):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Return a tzinfo instance with a fixed offset from UTC."""
|
2013-09-08 15:04:31 +08:00
|
|
|
if isinstance(offset, timedelta):
|
2017-10-25 03:42:44 +08:00
|
|
|
offset = offset.total_seconds() // 60
|
2013-09-08 15:04:31 +08:00
|
|
|
sign = '-' if offset < 0 else '+'
|
|
|
|
hhmm = '%02d%02d' % divmod(abs(offset), 60)
|
|
|
|
name = sign + hhmm
|
2018-07-10 04:33:36 +08:00
|
|
|
return timezone(timedelta(minutes=offset), name)
|
2013-09-08 15:04:31 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2014-11-19 04:50:03 +08:00
|
|
|
# In order to avoid accessing settings at compile time,
|
|
|
|
# wrap the logic in a function and cache the result.
|
2017-01-19 04:30:21 +08:00
|
|
|
@functools.lru_cache()
|
2011-11-18 21:01:06 +08:00
|
|
|
def get_default_timezone():
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Return the default time zone as a tzinfo instance.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
This is the time zone defined by settings.TIME_ZONE.
|
|
|
|
"""
|
2016-10-08 09:06:49 +08:00
|
|
|
return pytz.timezone(settings.TIME_ZONE)
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
# This function exists for consistency with get_current_timezone_name
|
|
|
|
def get_default_timezone_name():
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Return the name of the default time zone."""
|
2011-11-18 21:01:06 +08:00
|
|
|
return _get_timezone_name(get_default_timezone())
|
|
|
|
|
2016-11-13 01:11:23 +08:00
|
|
|
|
2019-04-12 21:15:18 +08:00
|
|
|
_active = Local()
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def get_current_timezone():
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Return the currently active time zone as a tzinfo instance."""
|
2011-11-18 21:01:06 +08:00
|
|
|
return getattr(_active, "value", get_default_timezone())
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def get_current_timezone_name():
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Return the name of the currently active time zone."""
|
2011-11-18 21:01:06 +08:00
|
|
|
return _get_timezone_name(get_current_timezone())
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def _get_timezone_name(timezone):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Return the name of ``timezone``."""
|
2018-03-04 03:56:39 +08:00
|
|
|
return timezone.tzname(None)
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
# Timezone selection functions.
|
|
|
|
|
|
|
|
# These functions don't change os.environ['TZ'] and call time.tzset()
|
|
|
|
# because it isn't thread safe.
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def activate(timezone):
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Set the time zone for the current thread.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
The ``timezone`` argument must be an instance of a tzinfo subclass or a
|
2016-10-08 09:06:49 +08:00
|
|
|
time zone name.
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
|
|
|
if isinstance(timezone, tzinfo):
|
|
|
|
_active.value = timezone
|
2016-12-29 23:27:49 +08:00
|
|
|
elif isinstance(timezone, str):
|
2011-11-18 21:01:06 +08:00
|
|
|
_active.value = pytz.timezone(timezone)
|
|
|
|
else:
|
|
|
|
raise ValueError("Invalid timezone: %r" % timezone)
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def deactivate():
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Unset the time zone for the current thread.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
Django will then use the time zone defined by settings.TIME_ZONE.
|
|
|
|
"""
|
|
|
|
if hasattr(_active, "value"):
|
|
|
|
del _active.value
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2014-08-31 02:06:38 +08:00
|
|
|
class override(ContextDecorator):
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
|
|
|
Temporarily set the time zone for the current thread.
|
|
|
|
|
2017-01-25 04:32:33 +08:00
|
|
|
This is a context manager that uses django.utils.timezone.activate()
|
|
|
|
to set the timezone on entry and restores the previously active timezone
|
2011-11-18 21:01:06 +08:00
|
|
|
on exit.
|
|
|
|
|
|
|
|
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
|
2016-10-08 09:06:49 +08:00
|
|
|
time zone name, or ``None``. If it is ``None``, Django enables the default
|
|
|
|
time zone.
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
|
|
|
def __init__(self, timezone):
|
|
|
|
self.timezone = timezone
|
|
|
|
|
|
|
|
def __enter__(self):
|
2014-08-29 04:26:37 +08:00
|
|
|
self.old_timezone = getattr(_active, 'value', None)
|
2011-11-18 21:01:06 +08:00
|
|
|
if self.timezone is None:
|
|
|
|
deactivate()
|
|
|
|
else:
|
|
|
|
activate(self.timezone)
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
2013-01-31 23:00:39 +08:00
|
|
|
if self.old_timezone is None:
|
|
|
|
deactivate()
|
2011-11-18 21:01:06 +08:00
|
|
|
else:
|
2013-01-31 23:00:39 +08:00
|
|
|
_active.value = self.old_timezone
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
|
2012-03-04 03:57:25 +08:00
|
|
|
# Templates
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2012-04-29 21:37:23 +08:00
|
|
|
def template_localtime(value, use_tz=None):
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Check if value is a datetime and converts it to local time if necessary.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
|
|
|
If use_tz is provided and is not None, that will force the value to
|
|
|
|
be converted (or not), overriding the value of settings.USE_TZ.
|
2012-03-04 03:57:25 +08:00
|
|
|
|
|
|
|
This function is designed for use by the template engine.
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
2016-04-04 08:37:32 +08:00
|
|
|
should_convert = (
|
2018-06-28 21:26:41 +08:00
|
|
|
isinstance(value, datetime) and
|
2016-04-04 08:37:32 +08:00
|
|
|
(settings.USE_TZ if use_tz is None else use_tz) and
|
|
|
|
not is_naive(value) and
|
|
|
|
getattr(value, 'convert_to_local_time', True)
|
|
|
|
)
|
2012-04-29 21:37:23 +08:00
|
|
|
return localtime(value) if should_convert else value
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2012-03-04 03:57:25 +08:00
|
|
|
|
|
|
|
# Utilities
|
|
|
|
|
2016-09-01 08:19:33 +08:00
|
|
|
def localtime(value=None, timezone=None):
|
2012-04-29 21:37:23 +08:00
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Convert an aware datetime.datetime to local time.
|
2012-04-29 21:37:23 +08:00
|
|
|
|
2016-09-01 08:19:33 +08:00
|
|
|
Only aware datetimes are allowed. When value is omitted, it defaults to
|
|
|
|
now().
|
|
|
|
|
2012-04-29 21:37:23 +08:00
|
|
|
Local time is defined by the current time zone, unless another time zone
|
|
|
|
is specified.
|
|
|
|
"""
|
2016-09-01 08:19:33 +08:00
|
|
|
if value is None:
|
|
|
|
value = now()
|
2012-04-29 21:37:23 +08:00
|
|
|
if timezone is None:
|
|
|
|
timezone = get_current_timezone()
|
2016-11-05 19:33:22 +08:00
|
|
|
# Emulate the behavior of astimezone() on Python < 3.6.
|
|
|
|
if is_naive(value):
|
|
|
|
raise ValueError("localtime() cannot be applied to a naive datetime")
|
2017-06-20 05:59:59 +08:00
|
|
|
return value.astimezone(timezone)
|
2012-04-29 21:37:23 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2016-09-01 08:19:33 +08:00
|
|
|
def localdate(value=None, timezone=None):
|
|
|
|
"""
|
|
|
|
Convert an aware datetime to local time and return the value's date.
|
|
|
|
|
|
|
|
Only aware datetimes are allowed. When value is omitted, it defaults to
|
|
|
|
now().
|
|
|
|
|
|
|
|
Local time is defined by the current time zone, unless another time zone is
|
|
|
|
specified.
|
|
|
|
"""
|
|
|
|
return localtime(value, timezone).date()
|
|
|
|
|
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def now():
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Return an aware or naive datetime.datetime, depending on settings.USE_TZ.
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
2018-06-28 21:26:41 +08:00
|
|
|
if settings.USE_TZ:
|
|
|
|
# timeit shows that datetime.now(tz=utc) is 24% slower
|
|
|
|
return datetime.utcnow().replace(tzinfo=utc)
|
|
|
|
else:
|
|
|
|
return datetime.now()
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-11-25 17:25:43 +08:00
|
|
|
# By design, these four functions don't perform any checks on their arguments.
|
|
|
|
# The caller should ensure that they don't receive an invalid value like None.
|
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def is_aware(value):
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Determine if a given datetime.datetime is aware.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2015-05-02 20:02:39 +08:00
|
|
|
The concept is defined in Python's docs:
|
2018-09-26 14:48:47 +08:00
|
|
|
https://docs.python.org/library/datetime.html#datetime.tzinfo
|
2015-05-02 20:02:39 +08:00
|
|
|
|
|
|
|
Assuming value.tzinfo is either None or a proper datetime.tzinfo,
|
|
|
|
value.utcoffset() implements the appropriate logic.
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
2015-05-02 20:02:39 +08:00
|
|
|
return value.utcoffset() is not None
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def is_naive(value):
|
|
|
|
"""
|
2017-01-25 04:32:33 +08:00
|
|
|
Determine if a given datetime.datetime is naive.
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2015-05-02 20:02:39 +08:00
|
|
|
The concept is defined in Python's docs:
|
2018-09-26 14:48:47 +08:00
|
|
|
https://docs.python.org/library/datetime.html#datetime.tzinfo
|
2015-05-02 20:02:39 +08:00
|
|
|
|
|
|
|
Assuming value.tzinfo is either None or a proper datetime.tzinfo,
|
|
|
|
value.utcoffset() implements the appropriate logic.
|
2011-11-18 21:01:06 +08:00
|
|
|
"""
|
2015-05-02 20:02:39 +08:00
|
|
|
return value.utcoffset() is None
|
2011-11-18 21:01:06 +08:00
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2015-03-31 13:58:37 +08:00
|
|
|
def make_aware(value, timezone=None, is_dst=None):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Make a naive datetime.datetime in a given time zone aware."""
|
2014-10-16 10:52:41 +08:00
|
|
|
if timezone is None:
|
|
|
|
timezone = get_current_timezone()
|
2011-11-18 21:01:06 +08:00
|
|
|
if hasattr(timezone, 'localize'):
|
2014-05-17 05:12:59 +08:00
|
|
|
# This method is available for pytz time zones.
|
2015-03-31 13:58:37 +08:00
|
|
|
return timezone.localize(value, is_dst=is_dst)
|
2011-11-18 21:01:06 +08:00
|
|
|
else:
|
2014-05-17 05:12:59 +08:00
|
|
|
# Check that we won't overwrite the timezone of an aware datetime.
|
|
|
|
if is_aware(value):
|
|
|
|
raise ValueError(
|
2014-05-18 00:54:34 +08:00
|
|
|
"make_aware expects a naive datetime, got %s" % value)
|
2014-05-17 05:12:59 +08:00
|
|
|
# This may be wrong around DST changes!
|
2011-11-18 21:01:06 +08:00
|
|
|
return value.replace(tzinfo=timezone)
|
|
|
|
|
2013-11-03 07:53:29 +08:00
|
|
|
|
2014-10-16 10:52:41 +08:00
|
|
|
def make_naive(value, timezone=None):
|
2017-01-25 04:32:33 +08:00
|
|
|
"""Make an aware datetime.datetime naive in a given time zone."""
|
2014-10-16 10:52:41 +08:00
|
|
|
if timezone is None:
|
|
|
|
timezone = get_current_timezone()
|
2016-11-05 19:33:22 +08:00
|
|
|
# Emulate the behavior of astimezone() on Python < 3.6.
|
|
|
|
if is_naive(value):
|
|
|
|
raise ValueError("make_naive() cannot be applied to a naive datetime")
|
2017-06-20 05:59:59 +08:00
|
|
|
return value.astimezone(timezone).replace(tzinfo=None)
|