Timezone¶
Introduction¶
The design of timezone is inspired by Django but also has differences. There are two config items use_tz and timezone affect timezone in tortoise, which can be set when call Tortoise.init. And in different DBMS there also are different behaviors.
Note
As of 1.0, pytz has been removed. Timezone handling uses Python’s standard library
zoneinfo module. All timezone objects returned by Tortoise are ZoneInfo instances.
use_tz¶
use_tz defaults to True. When enabled, all datetimes are stored as UTC in the database and tortoise.timezone.now() returns a timezone-aware datetime. MySQL uses DATETIME(6), PostgreSQL uses TIMESTAMPTZ, and SQLite uses TIMESTAMP for schema generation.
For TimeField, MySQL uses TIME(6), PostgreSQL uses TIMETZ, and SQLite uses TIME.
When use_tz = False, datetimes are stored and returned as naive (no timezone info). tortoise.timezone.now() returns a naive datetime in this mode.
timezone¶
The timezone setting determines what timezone is used when reading DateTimeField and TimeField from the database (only effective when use_tz = True). Use tortoise.timezone.now() to get the current time respecting your use_tz setting.
Reference¶
- tortoise.timezone.get_default_timezone()[source]¶
Return the default time zone as a tzinfo instance.
This is the time zone defined by Tortoise config.
- Return type:¶
tzinfo
- tortoise.timezone.get_timezone()[source]¶
Get timezone from env set in Tortoise config.
- Return type:¶
str
- tortoise.timezone.get_use_tz()[source]¶
Get use_tz from env set in Tortoise config.
- Return type:¶
bool
- tortoise.timezone.is_aware(value)[source]¶
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.
- Return type:¶
bool
- tortoise.timezone.is_naive(value)[source]¶
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.
- Return type:¶
bool
-
tortoise.timezone.localtime(value=
None, timezone=None)[source]¶ 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.
-
tortoise.timezone.make_aware(value, timezone=
None, is_dst=None)[source]¶ Make a naive datetime.datetime in a given time zone aware.
-
tortoise.timezone.make_naive(value, timezone=
None)[source]¶ Make an aware datetime.datetime naive in a given time zone.