Repository navigation
Description
Summary
DatetimeField timezone handling does not consistently honor the globally configured timezone (config["timezone"], exposed as the TIMEZONE env var). In tortoise-orm 1.1.8, two code paths ignore it:
1. auto_now / auto_now_add always use UTC
The timestamp is generated by timezone.now(), which returns UTC whenever use_tz=True (see the docstring in tortoise/timezone.py), regardless of the configured timezone. With timezone="Asia/Shanghai", a field such as created_at = fields.DatetimeField(auto_now_add=True) is persisted as UTC (+00:00) instead of following the global timezone setting.
2. to_db_value hardcodes UTC for naive input, while to_python_value uses the configured timezone
In tortoise/fields/data.py, writing a naive datetime interprets it as UTC:
value = timezone.make_aware(value, "UTC") # to_db_valuebut reading a naive value from the DB interprets it with the configured timezone:
value = timezone.make_aware(value, get_timezone()) # to_python_valueThis asymmetry causes write→read round-trips to drift by the UTC offset whenever a non-UTC timezone is configured (e.g. 8 hours for Asia/Shanghai).
Steps to reproduce
Configure timezone="Asia/Shanghai" (any non-UTC value):
- Save a row with a naive datetime, e.g.
datetime(2026, 9, 7, 9, 0). - Reload the row: the value comes back as
2026-09-07 17:00+08:00— the naive input was interpreted as UTC on write, then localized to Asia/Shanghai on read. 8-hour drift. - Separately,
auto_now_addtimestamps are stored as UTC while the application is configured for Asia/Shanghai, forcing every query on that column to deal with the offset mismatch.
Expected behavior
Timezone handling should prioritize the globally configured timezone consistently:
auto_now/auto_now_addshould generate the timestamp in the configured timezone (or, if storing UTC on disk is intentional, that should be documented and applied consistently — the current mix is surprising);to_db_valueshould interpret naive input with the configured timezone, symmetric withto_python_value.
Suggested fix
--- a/tortoise/fields/data.py
+++ b/tortoise/fields/data.py
@@ -489,7 +489,7 @@
if hasattr(instance, "_saved_in_db") and (
self.auto_now
or (self.auto_now_add and getattr(instance, self.model_field_name) is None)
):
- now = timezone.now()
+ now = datetime.datetime.now(get_default_timezone())
# Convert to match what would be read from DB (apply timezone conversion)
now_python = self.to_python_value(now)
setattr(instance, self.model_field_name, now_python)
return now # type:ignore[return-value]
@@ -502,7 +502,7 @@
if timezone.is_naive(value):
warnings.warn(
f"DateTimeField {self.model_field_name} received a naive datetime ({value})"
" while time zone support is active.",
RuntimeWarning,
)
- value = timezone.make_aware(value, "UTC")
+ value = timezone.make_aware(value, get_timezone())(get_default_timezone() and get_timezone() are already imported in this module.)
Environment
- tortoise-orm 1.1.8
- Python 3.11
- SQLite (WAL mode), issue is backend-agnostic
Activity
jagadeepmamidi commentedon Sep 7, 2026
Hi, I’d like to investigate this issue and add regression tests for datetime round-trips with a non-UTC timezone. The docs specify UTC storage with
use_tz=True, so I’d preserve that behavior. Could a maintainer confirm whether naive inputs should be interpreted in the configured timezone rather than UTC? I’m happy to work on the agreed fix.Fix naive DatetimeField timezone drift (tortoise#2277)
waketzheng commentedon Sep 16, 2026
@jagadeepmamidi, there are several things that can be done:
tortoise/models.py: UseSelfinstead ofMODELfor type hints.tortoise.run_asyncto accept thedb_url,modules,config,config_file, andverbosearguments.# TODOcomments intortoise/.ty checklint issues.ciso8601is unavailable, trydatetime.fromisoformatbefore falling back toiso8601.ModelClass.field_attrso thatawait ModelClass.filter().values_list(ModelClass.field_attr, flat=True)yields the correct type hint.waketzheng commentedon Nov 16, 2026
@jagadeepmamidi, I think the best solution is as follows:
use_tz=True'2026-11-16 22:43:01.012345+00:00'.use_tz=False'2026-11-16 22:43:01.012345'.tzinfo=Noneas stored in the database.ConfigureErrorif the timezone is not set.Nonebefore saving to the database.use_tz=NoneAlmost identical to
use_tz=False, except:ConfigureErrorif the timezone is not set.