#296·AI-Trader

datetime('now', '-N day') compares against ISO timestamps and widens every window by up to a day on SQLite

Author: LudwigJMarxCreated Sep 21, 2026Updated Sep 21, 2026

Summary

Eight queries filter with created_at >= datetime('now', '-N day'). SQLite's datetime() returns 2026-08-22 16:51:45, while the application writes 2026-08-22T16:35:36Z. The comparison is lexicographic, and T (0x54) sorts above the space (0x20), so every row from the boundary day is included regardless of its time. On PostgreSQL the same SQL is rewritten to an ISO string, so the two backends answer the same query differently.

Where

File Line Window
routes_signals.py 1329, 1330, 1331, 1396, 1397 7 day
routes_trading.py 357 7 day
team_matching.py 23, 33 30 day

The PostgreSQL rewrite is at database.py:182-190:

SELECT 1 WHERE created_at >= to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC') + INTERVAL '-30 day',
                                     'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')

That branch produces the T and Z the stored values use. The SQLite branch does not.

Environment

Commit d03ff6c
Python 3.14.7
sqlite3 3.53.4
OS macOS 26.6.2, arm64

Reproduction

>>> sqlite3.connect(":memory:").execute("SELECT datetime('now','-30 day')").fetchone()[0]
'2026-08-22 16:51:45'

The application writes timestamps through utc_now_iso_z, for example 2026-08-22T16:35:36Z.

  2026-08-22T00:00:01Z  >= '2026-08-22 16:35:36'  -> True
  2026-08-22T23:59:59Z  >= '2026-08-22 16:35:36'  -> True
  2026-08-21T23:59:59Z  >= '2026-08-22 16:35:36'  -> False

The first row is more than 30 days and 16 hours old and is still counted. A "7 day" window covers up to 8 days.

Not verified

  • Only the SQLite branch was run. The PostgreSQL rewrite was produced by calling database._replace_sqlite_datetime_functions on the literal SQL, not by executing it against a server.
  • The magnitude of the effect on real counts was not measured; the reproduction shows the boundary behaviour, not how many rows it moves in production.