timezonerelated classes and functions return a tzinfo instance with a fixed offset from utc if isinstanceoffset timedelta offset offset totalseconds 60 sign if offset 0 else hhmm 02d02d divmodabsoffset 60 name sign hhmm return timezonetimedeltaminutesoffset name in order to avoid accessing settings at compile time wrap the logic in a function and cache the result functools lrucache def getdefaulttimezone return zoneinfo zoneinfosettings timezone this function exists for consistency with getcurrenttimezonename def getdefaulttimezonename return the currently active time zone as a tzinfo instance return getattractive value getdefaulttimezone def getcurrenttimezonename return the offset for fixed offset timezones or the name of timezone if not set timezone selection functions these functions don t change os environ tz and call time tzset because it isn t thread safe set the time zone for the current thread the timezone argument must be an instance of a tzinfo subclass or a time zone name unset the time zone for the current thread django will then use the time zone defined by settings timezone temporarily set the time zone for the current thread this is a context manager that uses django utils timezone activate to set the timezone on entry and restores the previously active timezone on exit the timezone argument must be an instance of a tzinfo subclass a time zone name or none if it is none django enables the default time zone templates check if value is a datetime and converts it to local time if necessary if usetz is provided and is not none that will force the value to be converted or not overriding the value of settings usetz this function is designed for use by the template engine utilities convert an aware datetime datetime to local time 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 emulate the behavior of astimezone on python 3 6 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 an aware or naive datetime datetime depending on settings usetz 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 determine if a given datetime datetime is aware the concept is defined in python s docs https docs python orglibrarydatetime htmldatetime tzinfo assuming value tzinfo is either none or a proper datetime tzinfo value utcoffset implements the appropriate logic determine if a given datetime datetime is naive the concept is defined in python s docs https docs python orglibrarydatetime htmldatetime tzinfo assuming value tzinfo is either none or a proper datetime tzinfo value utcoffset implements the appropriate logic make a naive datetime datetime in a given time zone aware if timezone is none timezone getcurrenttimezone check that we won t overwrite the timezone of an aware datetime if isawarevalue raise valueerrormakeaware expects a naive datetime got s value this may be wrong around dst changes return value replacetzinfotimezone def makenaivevalue timezonenone emulate the behavior of astimezone on python 3 6 return a tzinfo instance with a fixed offset from utc in order to avoid accessing settings at compile time wrap the logic in a function and cache the result return the default time zone as a tzinfo instance this is the time zone defined by settings time_zone this function exists for consistency with get_current_timezone_name return the name of the default time zone return the currently active time zone as a tzinfo instance return the name of the currently active time zone return the offset for fixed offset timezones or the name of timezone if not set timezone selection functions these functions don t change os environ tz and call time tzset because it isn t thread safe set the time zone for the current thread the timezone argument must be an instance of a tzinfo subclass or a time zone name unset the time zone for the current thread django will then use the time zone defined by settings time_zone temporarily set the time zone for the current thread this is a context manager that uses django utils timezone activate to set the timezone on entry and restores the previously active timezone on exit the timezone argument must be an instance of a tzinfo subclass a time zone name or none if it is none django enables the default time zone templates check if value is a datetime and converts it to local time if necessary 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 this function is designed for use by the template engine utilities convert an aware datetime datetime to local time 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 emulate the behavior of astimezone on python 3 6 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 an aware or naive datetime datetime depending on settings use_tz 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 determine if a given datetime datetime is aware the concept is defined in python s docs https docs python org library datetime html datetime tzinfo assuming value tzinfo is either none or a proper datetime tzinfo value utcoffset implements the appropriate logic determine if a given datetime datetime is naive the concept is defined in python s docs https docs python org library datetime html datetime tzinfo assuming value tzinfo is either none or a proper datetime tzinfo value utcoffset implements the appropriate logic make a naive datetime datetime in a given time zone aware check that we won t overwrite the timezone of an aware datetime this may be wrong around dst changes make an aware datetime datetime naive in a given time zone emulate the behavior of astimezone on python 3 6
import functools
import zoneinfo
from contextlib import ContextDecorator
from datetime import datetime, timedelta, timezone, tzinfo

from asgiref.local import Local

from django.conf import settings

__all__ = [
    "get_fixed_timezone",
    "get_default_timezone",
    "get_default_timezone_name",
    "get_current_timezone",
    "get_current_timezone_name",
    "activate",
    "deactivate",
    "override",
    "localtime",
    "localdate",
    "now",
    "is_aware",
    "is_naive",
    "make_aware",
    "make_naive",
]


def get_fixed_timezone(offset):
    
    if isinstance(offset, timedelta):
        offset = offset.total_seconds() // 60
    sign = "-" if offset < 0 else "+"
    hhmm = "%02d%02d" % divmod(abs(offset), 60)
    name = sign + hhmm
    return timezone(timedelta(minutes=offset), name)




@functools.lru_cache
def get_default_timezone():
    
    return zoneinfo.ZoneInfo(settings.TIME_ZONE)



def get_default_timezone_name():
    
    return _get_timezone_name(get_default_timezone())


_active = Local()


def get_current_timezone():
    
    return getattr(_active, "value", get_default_timezone())


def get_current_timezone_name():
    
    return _get_timezone_name(get_current_timezone())


def _get_timezone_name(timezone):
    
    return timezone.tzname(None) or str(timezone)








def activate(timezone):
    
    if isinstance(timezone, tzinfo):
        _active.value = timezone
    elif isinstance(timezone, str):
        _active.value = zoneinfo.ZoneInfo(timezone)
    else:
        raise ValueError("Invalid timezone: %r" % timezone)


def deactivate():
    
    if hasattr(_active, "value"):
        del _active.value


class override(ContextDecorator):
    

    def __init__(self, timezone):
        self.timezone = timezone

    def __enter__(self):
        self.old_timezone = getattr(_active, "value", None)
        if self.timezone is None:
            deactivate()
        else:
            activate(self.timezone)

    def __exit__(self, exc_type, exc_value, traceback):
        if self.old_timezone is None:
            deactivate()
        else:
            _active.value = self.old_timezone





def template_localtime(value, use_tz=None):
    
    should_convert = (
        isinstance(value, datetime)
        and (settings.USE_TZ if use_tz is None else use_tz)
        and not is_naive(value)
        and getattr(value, "convert_to_local_time", True)
    )
    return localtime(value) if should_convert else value





def localtime(value=None, timezone=None):
    
    if value is None:
        value = now()
    if timezone is None:
        timezone = get_current_timezone()
    
    if is_naive(value):
        raise ValueError("localtime() cannot be applied to a naive datetime")
    return value.astimezone(timezone)


def localdate(value=None, timezone=None):
    
    return localtime(value, timezone).date()


def now():
    
    return datetime.now(tz=timezone.utc if settings.USE_TZ else None)






def is_aware(value):
    
    return value.utcoffset() is not None


def is_naive(value):
    
    return value.utcoffset() is None


def make_aware(value, timezone=None):
    
    if timezone is None:
        timezone = get_current_timezone()
    
    if is_aware(value):
        raise ValueError("make_aware expects a naive datetime, got %s" % value)
    
    return value.replace(tzinfo=timezone)


def make_naive(value, timezone=None):
    
    if timezone is None:
        timezone = get_current_timezone()
    
    if is_naive(value):
        raise ValueError("make_naive() cannot be applied to a naive datetime")
    return value.astimezone(timezone).replace(tzinfo=None)


def _datetime_ambiguous_or_imaginary(dt, tz):
    return tz.utcoffset(dt.replace(fold=not dt.fold)) != tz.utcoffset(dt)