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.

use_tz

When set use_tz = True, tortoise will always store UTC time in database no matter what timezone set. And MySQL use field type DATETIME(6), PostgreSQL use TIMESTAMPTZ, SQLite use TIMESTAMP when generate schema. For TimeField, MySQL use TIME(6), PostgreSQL use TIMETZ and SQLite use TIME.

timezone

The timezone determine what timezone is when select DateTimeField and TimeField from database, no matter what timezone your database is. And you should use tortoise.timezone.now() get aware time instead of native time datetime.datetime.now().

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.

Raises:

ValueError – when value is naive datetime

Return type:

datetime

tortoise.timezone.make_aware(value, timezone=None, is_dst=None)[source]

Make a naive datetime.datetime in a given time zone aware.

Raises:

ValueError – when value is not naive datetime

Return type:

datetime

tortoise.timezone.make_naive(value, timezone=None)[source]

Make an aware datetime.datetime naive in a given time zone.

Raises:

ValueError – when value is naive datetime

Return type:

datetime

tortoise.timezone.now()[source]

Return an aware datetime.datetime, depending on use_tz and timezone.

Return type:

datetime