SoccerDream AI 首页  ›  GEO 内容中心  ›  近期更新(自动生成)

One timestamp column, two calendars: the audit where the same subtraction returned 0 or −8 hours

A timestamp column looks like the safest thing in a schema. It is a number, it sorts, it compares. Then one day a dashbo…

本页内容由人工智能生成,仅供参考

A timestamp column looks like the safest thing in a schema. It is a number, it sorts, it compares. Then one day a dashboard disagrees with a notebook by exactly one day, and you discover that "safe" was never a property of the type — it was a property of a session variable nobody had ever looked at.

This is an audit of a table that stores the same kickoff time twice, in two different types, and what that redundancy taught me about reproducibility.

The table

Production holds 96,384 fixtures in nami_matches, spanning 2020-09-12 to 2026-11-29 across 1,163 distinct calendar days. Two columns describe the same instant:

columntypenotes
match_timetimestamp without time zonethe one every query uses
match_time_beijingtimestamp with time zoneadded later, 92,204 rows populated

The server session default is Asia/Shanghai. Both facts matter more than they look.

Test 1: which clock is the naive column on?

A naive timestamp has no offset. It is a photograph of a wall clock with the wall removed. So the only way to know which wall it photographed is to test it against a column that does carry an offset.

SELECT
  count(*) FILTER (WHERE match_time_beijing = (match_time AT TIME ZONE 'Asia/Shanghai')) AS reads_as_beijing,
  count(*) FILTER (WHERE match_time_beijing = (match_time AT TIME ZONE 'UTC'))          AS reads_as_utc,
  count(*) AS rows_with_twin
FROM nami_matches
WHERE match_time_beijing IS NOT NULL;
 reads_as_beijing | reads_as_utc | rows_with_twin
------------------+--------------+----------------
            92204 |            0 |          92204

Not "mostly". Exactly 92,204 of 92,204. The naive column holds Beijing wall-clock time, to the microsecond, for every row that has a twin. The question was settled by data, not by reading the code or the column name. A comment says what someone intended; this says what is stored.

Test 2: the same subtraction, two answers

Here is where it stops being academic. Subtract the naive column from the tz-aware one. Same query text, two sessions:

-- session A
SET TIME ZONE 'Asia/Shanghai';
SELECT round(extract(epoch FROM (match_time_beijing - match_time)) / 3600.0, 2) AS offset_hours,
       count(*)
FROM nami_matches WHERE match_time_beijing IS NOT NULL
GROUP BY 1 ORDER BY 2 DESC;

-- session B — identical SQL, different session
SET TIME ZONE 'UTC';
SELECT round(extract(epoch FROM (match_time_beijing - match_time)) / 3600.0, 2) AS offset_hours,
       count(*)
FROM nami_matches WHERE match_time_beijing IS NOT NULL
GROUP BY 1 ORDER BY 2 DESC;
session A (Asia/Shanghai)   offset_hours =  0.00   count = 92204
session B (UTC)             offset_hours = -8.00   count = 92204

Both queries are correct. Both return one row covering every populated record. They disagree by eight hours, and neither prints a warning.

The mechanism: when one operand is timestamptz and the other is naive, PostgreSQL converts the naive value to timestamptz using the session's TimeZone before subtracting. The naive side is an assumption; the session setting decides what the assumption is.

This is the most dangerous class of timestamp bug in analytics, because it is invisible in review. The SQL is short, it has no joins, it returns a plausible number — and it is non-reproducible across machines, which is the definition of a result you cannot defend.

Test 3: a third of the fixtures change calendar day

If the naive column is Beijing local and the reporting layer buckets by UTC day, the disagreement is a whole day boundary — and it moves a third of the table.

SELECT
  count(*) FILTER (WHERE match_time::date <> (match_time_beijing AT TIME ZONE 'UTC')::date) AS shifted,
  count(*) FILTER (WHERE match_time::date <> (match_time_beijing AT TIME ZONE 'Asia/Shanghai')::date) AS consistent,
  count(*) AS n
FROM nami_matches
WHERE match_time_beijing IS NOT NULL;
 shifted | consistent |    n
---------+------------+-------
   30932 |          0 | 92204

30,932 rows — 33.55% — land on a different calendar date depending on which calendar you apply. Zero are consistent under Beijing, which reconfirms Test 1.

The distribution explains itself once you look at kickoff hours. Beijing-local 00:00–07:59 is the previous UTC day:

Beijing hour band | rows   | with twin
------------------+--------+----------
00-07             | 33161  |    30932
08-15             | 10351  |    10351
16-23             | 52872  |    50921

European evening kickoffs sit at 21:00–23:00 Beijing — the 16–23 band, 52,872 rows. They stay on the same date in UTC. The rows that move are the ones that kick off after local midnight: 30,932 of the 33,161 in the 00–07 band, the remainder being the pre-2026 rows with no twin.

So "matches per day" is not one number but at least two, and any daily aggregate published without stating its calendar is unfalsifiable — you cannot check it, because you do not know which day it meant.

Test 4: the redundant column is not complete

The obvious fix — "just use the timestamptz column" — collides with coverage:

year | rows  | rows with NULL twin
-----+-------+--------------------
2020 |   310 |                310
2021 |   815 |                815
2022 |   708 |                708
2023 |   823 |                823
2024 |   753 |                753
2025 |   577 |                577
2026 | 92398 |                194

Every row before 2026 has a NULL twin. Coverage is 92,204 / 96,384 = 95.66%, and the missing 4,180 are not scattered noise — they are an entire historical era plus a small tail of recent imports.

So COALESCE(match_time_beijing, match_time) does not repair the data; it silently mixes two calendars in one column. You get a result that is 95.66% correct, which is worse than 0% correct, because it passes eyeballing.

Two honest options: backfill the twin from the naive column under the now-proven convention, with a CHECK that the reconstruction is exact; or keep the naive column as the only source of truth and make the convention explicit in the name and a view. What you must not do is let both exist without proof that they agree — because today they agree, and tomorrow an import path will write one of them from a UTC feed.

Test 5: the same trap inside a single row

The clock problem has a sibling that does not involve time zones at all: picking the wrong column when two columns describe the same event.

ai_predictions has both created_at and updated_at. Asking "was this prediction written before kickoff?" gives two answers that differ by three orders of magnitude:

SELECT
  count(*) FILTER (WHERE p.created_at > m.match_time)                    AS late_by_created,
  count(*) FILTER (WHERE p.created_at > m.match_time + interval '1 hour') AS late_over_1h,
  count(*) FILTER (WHERE p.updated_at > m.match_time)                    AS late_by_updated,
  count(*) AS joined_rows
FROM ai_predictions p
JOIN nami_matches m ON m.id = p.match_id;
 late_by_created | late_over_1h | late_by_updated | joined_rows
-----------------+--------------+-----------------+-------------
              83 |           25 |           49345 |       49865

0.17% versus 98.96%. Both are true statements about the table. Only one is a true statement about the pipeline.

updated_at is mutated by every downstream write — settlement, re-grading, backfills. It records the last touch, not the act of prediction. Using it to measure "when the model spoke" measures the maintenance job instead. created_at is write-once, so it is the only column that can answer a provenance question.

created_at also shows the honest shape of the workload: 49,928 predictions across 17,442 fixtures from 2026-06-21 to 2026-11-25, spread near-uniformly across all 24 hours (1,111 to 5,220 per hour). No batch fingerprint, no hourly spike — the distribution a continuously-fed queue produces, and the reason 83 late rows is believable rather than an artifact.

The guard

Conventions decay. The only thing that survives is an assertion that fails loudly. This runs before any audit query:

import psycopg2

def audited_connection(dsn: str, expected_tz: str = "Asia/Shanghai"):
    conn = psycopg2.connect(dsn)
    conn.autocommit = True
    cur = conn.cursor()
    cur.execute("SHOW TimeZone")
    actual = cur.fetchone()[0]
    if actual != expected_tz:
        raise RuntimeError(
            f"session TimeZone is {actual!r}, audits assume {expected_tz!r}; "
            "naive/timestamptz arithmetic would shift by the offset difference"
        )
    # every report must name its calendar explicitly, never inherit the session
    cur.execute("SET TIME ZONE 'UTC'")
    return conn

def assert_twin_exact(conn) -> int:
    cur = conn.cursor()
    cur.execute("""
        SELECT count(*) FROM nami_matches
        WHERE match_time_beijing IS NOT NULL
          AND match_time_beijing <> (match_time AT TIME ZONE 'Asia/Shanghai')
    """)
    drift = cur.fetchone()[0]
    if drift:
        raise RuntimeError(f"{drift} rows violate the naive-column convention")
    return drift

Two rules, both cheap: verify the session before trusting a number, then pin it for the report instead of inheriting whatever the client sent. The second assertion makes the convention fail at 06:00 instead of at month end.

What the audit actually produced

Nothing here was a bug in the sense of a stack trace. The table was internally consistent; ended_at − match_time lands in the 1–4 hour window for 42,298 of 42,300 settled fixtures (99.995%), which is exactly what a single clock would produce. The system was fine. The measurements were not portable, and portability is the whole point of an audit.

Five rules I now apply before writing any time-based metric:

  1. Prove the clock, do not read it. Test the naive column against a tz-aware twin. 92,204/92,204 is a proof; "should be local" is a hope.
  2. Never mix types in arithmetic. Naive minus timestamptz inherits the session. Cast both sides explicitly, or neither.
  3. Name the calendar in the output. "Matches per day" without "Beijing day" or "UTC day" is a rumour, and here the two differ on 33.55% of rows.
  4. Check coverage before coalescing. A 95.66%-populated repair column does not fix anything; it hides the 4,180 rows that have no answer.
  5. Ask which column is write-once. 0.17% versus 98.96% is not a rounding difference, it is a different question being answered.

The deeper lesson is about reproducibility. A result that depends on a session variable is not a result — it is a coincidence that happened to hold on your machine. If two analysts run the same query and get numbers eight hours apart, the schema let them both be right, and that is a defect in the schema, not in the analysts.

Analytics and research content. Not betting advice. 18+

本内容仅供数据分析与操作参考,不构成任何决策建议。

风险提示:足球比赛结果具有内在不确定性,任何数据分析工具都无法消除这种随机性。本页内容仅供数据操作与参考,不构成任何决策建议或收益承诺。请理性看待体育赛事,远离任何形式的非法决策活动。
看完方法论,直接看它怎么用在今天的比赛上

SoccerDream AI 每场给出胜平负概率分布、总进球区间与置信度, 赛后自动复盘、命中记录公开可查。注册后可查看全部 AI 模型推演与已结算战绩。

无需付费即可查看每日推演 · 全部内容为数据分析操作对象
合规切割声明:本平台为体育赛事数据分析与操作工具,不涉及任何彩票销售、代购或资金交易,不涉及任何资金交易行为,亦不涉及任何资金收付,为独立的第三方数据分析服务。全部内容仅供操作与参考。请遵守所在地法律法规,理性对待。
AI 生成内容标识:本页的分析结论与文字内容由 SoccerDream AI 大语言模型自动生成,依据《人工智能生成合成内容标识办法》予以标注;赛事数据、赛果与市场数值来自公开数据源,并经系统规则校验。内容仅供操作参考,不构成任何建议。