[docs]defget_use_tz()->bool:""" Get use_tz from env set in Tortoise config. """returnos.environ.get("USE_TZ")=="True"
[docs]defget_timezone()->str:""" Get timezone from env set in Tortoise config. """returnos.environ.get("TIMEZONE")or"UTC"
[docs]defnow()->datetime:""" Return an aware datetime.datetime, depending on use_tz and timezone. """ifget_use_tz():returndatetime.now(tz=pytz.utc)else:returndatetime.now(get_default_timezone())
[docs]defget_default_timezone()->tzinfo:""" Return the default time zone as a tzinfo instance. This is the time zone defined by Tortoise config. """returnpytz.timezone(get_timezone())
[docs]deflocaltime(value:Optional[datetime]=None,timezone:Optional[str]=None)->datetime:""" Convert an aware datetime.datetime to local time. Only aware datetime 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. :raises ValueError: when value is naive datetime """ifvalueisNone:value=now()tz=get_default_timezone()iftimezoneisNoneelsepytz.timezone(timezone)ifis_naive(value):raiseValueError("localtime() cannot be applied to a naive datetime")returnvalue.astimezone(tz)
[docs]defis_aware(value:Union[datetime,time])->bool:""" Determine if a given datetime.datetime or datetime.time 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. """returnvalue.utcoffset()isnotNone
[docs]defis_naive(value:Union[datetime,time])->bool:""" Determine if a given datetime.datetime or datetime.time 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. """returnvalue.utcoffset()isNone
[docs]defmake_aware(value:datetime,timezone:Optional[str]=None,is_dst:Optional[bool]=None)->datetime:""" Make a naive datetime.datetime in a given time zone aware. :raises ValueError: when value is not naive datetime """tz=get_default_timezone()iftimezoneisNoneelsepytz.timezone(timezone)ifhasattr(tz,"localize"):returntz.localize(value,is_dst=is_dst)ifis_aware(value):raiseValueError("make_aware expects a naive datetime, got %s"%value)# This may be wrong around DST changes!returnvalue.replace(tzinfo=tz)
[docs]defmake_naive(value:datetime,timezone:Optional[str]=None)->datetime:""" Make an aware datetime.datetime naive in a given time zone. :raises ValueError: when value is naive datetime """tz=get_default_timezone()iftimezoneisNoneelsepytz.timezone(timezone)ifis_naive(value):raiseValueError("make_naive() cannot be applied to a naive datetime")returnvalue.astimezone(tz).replace(tzinfo=None)