Why You Should Store Every Timestamp in UTC (With JS, Python and SQL Examples)

Why You Should Store Every Timestamp in UTC (With JS, Python and SQL Examples)

每一位处理日期的开发者最终都会遇到同一个错误。一份报告显示昨天的订单出现在今天;一个提醒在三月份提前了一小时触发;悉尼的一位用户看到一个从未存在过的时间点的会议。几乎所有这些错误都源于项目早期做出的一个决定:存储本地时间而不是 UTC。以下是我在每个项目中遵循的规则、它有效的原因,以及如何在 JavaScript、Python 和 SQL 中应用它。

The rule: store in UTC, convert at the edges Store every timestamp in UTC. Convert to a user’s local time only at the very last moment, when you display it. Convert user input from local time to UTC at the very first moment, when you receive it. Inside your system, between those two edges, there is only one clock.

规则:存储为 UTC,在边缘处转换 将每个时间戳都存储为 UTC。仅在最后展示给用户时,才将其转换为用户的本地时间。在接收用户输入的第一时间,就将其从本地时间转换为 UTC。在你的系统内部,在这两个边缘之间,只存在一个时钟。

Why local time breaks things

  1. Daylight saving creates missing and duplicate hours. In the US, clocks jump from 2:00 AM to 3:00 AM on the second Sunday of March. A local time of 2:30 AM that night simply does not exist. In November the clocks fall back, and 1:30 AM happens twice. UTC never jumps, so every moment has exactly one value.
  2. Users and servers move. Your server might run in Virginia today and Frankfurt next year. Your users travel. If you store local time, you also need to store whose local time it was, and most schemas forget that.

为什么本地时间会引发问题

  1. 夏令时会导致时间缺失或重复。在美国,三月的第二个星期日,时钟会从凌晨 2:00 跳到 3:00。那天晚上凌晨 2:30 的本地时间根本不存在。在十一月,时钟会回拨,凌晨 1:30 会出现两次。UTC 从不跳变,因此每一个时刻都有且仅有一个值。

  2. 用户和服务器会移动。你的服务器今天可能在弗吉尼亚运行,明年可能在法兰克福。你的用户也会旅行。如果你存储的是本地时间,你还需要存储这是谁的本地时间,而大多数数据库模式都忽略了这一点。

  3. Sorting and comparing get unreliable. Two local timestamps from different zones cannot be compared without extra context. Two UTC timestamps can always be compared directly.

  4. Daylight saving dates differ by country. The US and Europe switch clocks on different Sundays. For a few weeks each year the gap between New York and London is four hours instead of five. Code that hardcodes offsets breaks twice a year.

  5. 排序和比较变得不可靠。如果没有额外的上下文,来自不同时区的两个本地时间戳无法进行比较。而两个 UTC 时间戳总是可以直接比较的。

  6. 不同国家的夏令时日期不同。美国和欧洲在不同的星期日切换时钟。每年有几周时间,纽约和伦敦之间的时差是四小时而不是五小时。硬编码偏移量的代码每年会出错两次。

How to do it in practice JavaScript // Get the current moment as an ISO string in UTC const now = new Date().toISOString(); // ends with “Z”, which means UTC // Store “now”. Format only when you display it: const display = new Date(now).toLocaleString(“en”, { timeZone: “America/New_York”, dateStyle: “medium”, timeStyle: “short”, }); The Z at the end of the string is Zulu time, another name for UTC. If you ever see an ISO string without a Z or an offset, treat it as a bug waiting to happen.

实践方法 JavaScript // 以 UTC ISO 字符串格式获取当前时刻 const now = new Date().toISOString(); // 以 “Z” 结尾,表示 UTC // 存储 “now”。仅在展示时进行格式化: const display = new Date(now).toLocaleString(“en”, { timeZone: “America/New_York”, dateStyle: “medium”, timeStyle: “short”, }); 字符串末尾的 Z 是祖鲁时间(Zulu time),即 UTC 的别名。如果你看到一个没有 Z 或偏移量的 ISO 字符串,请将其视为一个即将发生的错误。

Python from datetime import datetime, timezone from zoneinfo import ZoneInfo

Always create aware datetimes in UTC

now = datetime.now(timezone.utc)

Convert only for display

local = now.astimezone(ZoneInfo(“Asia/Karachi”)) Avoid datetime.utcnow(). It returns a naive datetime with no time zone attached, and it is deprecated in recent Python versions.

Python from datetime import datetime, timezone from zoneinfo import ZoneInfo

始终创建包含时区信息的 UTC 时间

now = datetime.now(timezone.utc)

仅在展示时进行转换

local = now.astimezone(ZoneInfo(“Asia/Karachi”)) 避免使用 datetime.utcnow()。它返回的是不带时区的“朴素”(naive)时间,且在近期的 Python 版本中已被弃用。

SQL (PostgreSQL) CREATE TABLE orders ( id bigserial PRIMARY KEY, created_at timestamptz NOT NULL DEFAULT now() ); Use timestamptz, not timestamp. PostgreSQL stores timestamptz values in UTC internally and converts them using the session time zone when you read them. Setting the session or database time zone to UTC keeps what you see consistent with what is stored.

SQL (PostgreSQL) CREATE TABLE orders ( id bigserial PRIMARY KEY, created_at timestamptz NOT NULL DEFAULT now() ); 使用 timestamptz,而不是 timestamp。PostgreSQL 在内部以 UTC 存储 timestamptz 值,并在读取时使用会话时区进行转换。将会话或数据库时区设置为 UTC,可以确保你看到的内容与存储的内容保持一致。

Store the user’s time zone separately UTC tells you when something happened. It does not tell you where. For features like “send this reminder at 9 AM my time every day”, store the user’s IANA time zone name, such as Europe/London or America/Chicago, in their profile. Never store a fixed offset like “UTC plus 1”, because that offset changes with daylight saving.

单独存储用户的时区 UTC 告诉你某事发生的时间,但不能告诉你地点。对于“每天在我当地时间上午 9 点发送提醒”这类功能,请在用户资料中存储其 IANA 时区名称,例如 Europe/London 或 America/Chicago。永远不要存储像“UTC 加 1”这样的固定偏移量,因为该偏移量会随夏令时而改变。

A quick checklist

  • Every timestamp column is UTC or timestamptz.
  • Every API sends and receives ISO 8601 strings with a Z or an explicit offset.
  • Servers and containers run with their system clock set to UTC.
  • User time zones are stored as IANA names, not offsets.
  • Conversion to local time happens only in the UI layer.
  • Recurring events are calculated in the user’s zone, then stored in UTC.

快速检查清单

  • 每个时间戳列都应为 UTC 或 timestamptz 类型。
  • 每个 API 发送和接收的都应是带有 Z 或明确偏移量的 ISO 8601 字符串。
  • 服务器和容器运行时的系统时钟应设置为 UTC。
  • 用户时区应存储为 IANA 名称,而非偏移量。
  • 转换为本地时间的操作仅在 UI 层进行。
  • 周期性事件应在用户时区计算,然后以 UTC 存储。

Tools that make debugging easier When you are checking logs or comparing timestamps across services, it helps to keep the actual current UTC time visible instead of doing mental math. I keep a tab open with the current UTC time so I can match log entries against real time and convert to local zones in one glance.

让调试更轻松的工具 当你检查日志或跨服务比较时间戳时,保持当前实际的 UTC 时间可见,比进行心算更有帮助。我常开一个标签页显示当前的 UTC 时间,这样我就可以将日志条目与真实时间进行匹配,并一眼转换到本地时区。

Make UTC your default today Time zone bugs are expensive because they hide until a daylight saving weekend or a user in a new country finds them. Pick one rule and apply it everywhere: store in UTC, convert at the edges, and save the user’s zone by name. Open your schema today, check your timestamp columns, and fix the first one that is not UTC. Your future self will thank you the next time the clocks change.

从今天起将 UTC 作为默认设置 时区错误代价高昂,因为它们会一直隐藏,直到夏令时周末或身处新国家的用户发现它们。选择一个规则并到处应用它:存储为 UTC,在边缘处转换,并按名称保存用户的时区。今天就打开你的数据库模式,检查你的时间戳列,并修复第一个不是 UTC 的列。当下一次时钟变动时,未来的你会感谢现在的自己。