Skip to content

DatetimeField timezone handling does not prioritize the globally configured timezone #2273

Closed

Description

@long-wang-lgtm

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_value

but reading a naive value from the DB interprets it with the configured timezone:

value = timezone.make_aware(value, get_timezone())   # to_python_value

This 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):

  1. Save a row with a naive datetime, e.g. datetime(2026, 9, 7, 9, 0).
  2. 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.
  3. Separately, auto_now_add timestamps 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_add should 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_value should interpret naive input with the configured timezone, symmetric with to_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

  1. jagadeepmamidi commented on Sep 7, 2026

    @jagadeepmamidi

    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.

  2. added a commit that references this issue on Sep 11, 2026
    0a454c1
  3. waketzheng commented on Sep 16, 2026

    @waketzheng
    Contributor

    @jagadeepmamidi, there are several things that can be done:

    • tortoise/models.py: Use Self instead of MODEL for type hints.
    • Enhance tortoise.run_async to accept the db_url, modules, config, config_file, and verbose arguments.
    • Resolve # TODO comments in tortoise/.
    • Upgrade Ruff and fix lint issues.
    • Fix ty check lint issues.
    • When ciso8601 is unavailable, try datetime.fromisoformat before falling back to iso8601.
    • Support ModelClass.field_attr so that await ModelClass.filter().values_list(ModelClass.field_attr, flat=True) yields the correct type hint.
  4. waketzheng commented on Nov 16, 2026

    @waketzheng
    Contributor

    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.

    @jagadeepmamidi, I think the best solution is as follows:

    1. use_tz=True

      • Store datetimes with UTC tzinfo in the database, e.g., '2026-11-16 22:43:01.012345+00:00'.
      • Convert values read from the database to the custom timezone if one is configured in the global settings.
      • Emit a warning when attempting to save a naive datetime, but still trust the global timezone setting and convert it to UTC before saving.
    2. use_tz=False

      • Store datetimes without tzinfo in the database, e.g., '2026-11-16 22:43:01.012345'.
      • Ignore tzinfo and return datetimes with tzinfo=None as stored in the database.
      • Raise ConfigureError if the timezone is not set.
      • Convert an aware datetime's tzinfo to the custom timezone, then replace tzinfo with None before saving to the database.
      • Leave naive datetimes unchanged.
    3. use_tz=None

      Almost identical to use_tz=False, except:

      • Do not raise ConfigureError if the timezone is not set.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions