Sub topic 15
Guidelines for time zone safe schemas
This chapter turns the earlier material into design rules. It assumes you know the difference between timestamp and timestamptz, how the session TimeZone setting affects output, how AT TIME ZONE converts values, and why half-open ranges work. Each rule below shows the bug it prevents.
Pick the column type by what the value means
Most time zone bugs start with the wrong column type. Decide what the value represents before you choose a type.
| The value is... | Use | Example |
|---|---|---|
| An exact moment that happened or will happen | `timestamptz` | order placed, payment received, deploy finished |
| A calendar date with no time of day | `date` | birthday, invoice due date |
| A local wall-clock time in a known place | `timestamp` plus a zone name column | "every Monday 09:00 in Paris" |
| A length of time | `interval` | trial period, retention window |
Two types rarely belong in a schema. timetz is discouraged by the PostgreSQL documentation, because a time of day with a fixed offset cannot follow daylight saving rules. A bare timestamp that actually holds UTC values is a bug waiting to happen, because nothing in the type says which zone it means.
Rule 1: store instants as timestamptz
If a value names a real moment, use timestamptz. PostgreSQL stores it as an absolute instant and converts it to the session zone only on output. Two clients in different zones then read the same instant, each in its own local form.
CREATE TABLE audit_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
action text NOT NULL,
logged_at timestamptz NOT NULL DEFAULT now()
);now() returns the transaction start time as a timestamptz, so every row written in one transaction gets the same value. Use clock_timestamp() only when you need the actual wall-clock reading at the moment of the call.
Audit existing schemas
You can list every timestamp without time zone column and review each one.
SELECT table_schema, table_name, column_name
FROM information_schema.columns
WHERE data_type = 'timestamp without time zone'
AND table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY table_schema, table_name, column_name;For each hit, decide whether the column is an instant (convert it) or a deliberate wall-clock value (keep it and document it). If you know the stored values were UTC, convert them like this:
ALTER TABLE audit_log
ALTER COLUMN logged_at TYPE timestamptz
USING logged_at AT TIME ZONE 'UTC';The USING clause matters. Without it, PostgreSQL would interpret the old values in whatever the session TimeZone happens to be. The statement takes an ACCESS EXCLUSIVE lock and can rewrite the table, so schedule it for a quiet period on large tables.
Rule 2: for future local times, store the wall clock and the zone name
An instant is the wrong model for "the weekly meeting is at 09:00 Paris time". If the European DST rules change, or the meeting crosses a DST change, 09:00 local stays 09:00 local, while the UTC instant shifts by an hour. Storing a precomputed UTC instant would put the meeting at the wrong local time after the change.
Store the local wall-clock value and the IANA zone name separately, and compute the instant when you need it.
CREATE TABLE zone (
name text PRIMARY KEY
);
INSERT INTO zone (name)
SELECT name FROM pg_timezone_names;
CREATE TABLE meeting (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
local_start timestamp NOT NULL,
tz_name text NOT NULL REFERENCES zone (name)
);
INSERT INTO meeting (title, local_start, tz_name)
VALUES ('planning', '2025-03-31 09:00:00', 'Europe/Paris');
SELECT title, local_start AT TIME ZONE tz_name AS starts_at
FROM meeting;The foreign key rejects typos such as Europe/Pariss at insert time. A CHECK constraint cannot do this job, because it cannot query pg_timezone_names. The AT TIME ZONE expression turns the plain timestamp into a timestamptz, as covered in the conversion chapter.
For times that have already happened, store the instant instead. Past instants never change.
Local times can be invalid or repeated
Two kinds of local time cause trouble. A time inside the spring-forward gap, such as 02:30 on the day clocks jump from 02:00 to 03:00, never occurs. A time inside the fall-back hour occurs twice. PostgreSQL does not raise an error for either one. It silently picks an interpretation. If users type local times, validate them in the application or present the choice to the user.
Rule 3: set TimeZone explicitly
The session TimeZone setting controls how timestamptz input without an offset is read and how output is displayed. If you leave it to chance, it comes from the server config, the database, the role, or the client library, and different connections may disagree.
Pick a default and set it at the database or role level:
ALTER DATABASE app SET TimeZone = 'UTC';
ALTER ROLE report_reader SET TimeZone = 'America/New_York';Settings made with ALTER DATABASE and ALTER ROLE apply to new sessions only. A role setting overrides a database setting. For a request that should display in the user's zone, scope the change to one transaction so it cannot leak into the next request that reuses a pooled connection:
BEGIN;
SET LOCAL TimeZone = 'Asia/Tokyo';
SELECT starts_at FROM event;
COMMIT;Rule 4: use zone names, not abbreviations or fixed offsets
'America/New_York' carries the full history of DST rules. 'EST' is a fixed offset of UTC-5 with no DST. A fixed offset such as '-05:00' is also fixed. Abbreviations can also be ambiguous: CST means different things in different countries. Fixed offsets are correct only when the source of the data really gave you a fixed offset, for example an ISO 8601 string from an API. Everywhere else, use the IANA name.
You can list the valid names and their current offsets:
SELECT name, abbrev, utc_offset, is_dst
FROM pg_timezone_names
WHERE name LIKE 'Europe/%'
ORDER BY name
LIMIT 5;Rule 5: bucket by local day after converting, and filter with half-open ranges
"Events per day" has no answer until you say whose day. Convert to the target zone first, then truncate:
SELECT date_trunc('day', starts_at AT TIME ZONE 'America/New_York') AS local_day,
count(*) AS events
FROM event
GROUP BY 1
ORDER BY 1;This produces a plain timestamp for each local day. For filtering, do not wrap the column in a function. Compute the boundaries as instants and compare the raw column. A local day on a DST change is 23 or 25 hours long, so the range must be built from two local midnights, not from "start plus 24 hours":
SELECT *
FROM event
WHERE starts_at >= TIMESTAMP '2024-03-10 00:00:00' AT TIME ZONE 'America/New_York'
AND starts_at < TIMESTAMP '2024-03-11 00:00:00' AT TIME ZONE 'America/New_York';This query covers a 23-hour day correctly. It also keeps a plain B-tree index on starts_at usable, because the column is compared directly. A filter such as WHERE date_trunc('day', starts_at AT TIME ZONE '...') = ... cannot use that index unless you create an expression index with the same expression.
Rule 6: choose interval units on purpose
Intervals hold months, days, and a time part separately, and each unit behaves differently when added to a timestamptz:
interval '1 month'follows the calendar and clamps to the last day of a shorter month.interval '1 day'keeps the local clock time, even across a DST change.interval '24 hours'adds exactly 24 elapsed hours.
Use 1 day for "the same time tomorrow", such as a reminder. Use 24 hours for "exactly one day of elapsed time later", such as a cache expiry. Run the arithmetic with the session TimeZone set to the zone whose calendar you mean, because that zone decides what "a day" is.
Rule 7: keep conversion at the edges
A practical architecture follows one pattern:
- Store instants as
timestamptz, and local times astimestampplus a zone name. - Run the database with a fixed server-side
TimeZone, usually UTC. - Convert to a user's zone at the last step, either with
AT TIME ZONEin the query or in the application's formatting layer. - Send timestamps between services in ISO 8601 with an explicit offset, such as
2024-06-01T09:00:00+02:00.
This keeps business logic comparing instants, and leaves display decisions to code that knows who is looking.
Checklist
- No
timestampcolumn holds a value that is really an instant. - Every
timestampthat holds local time has a zone name column with a foreign key. TimeZoneis set explicitly on the database or role, and per-request changes useSET LOCAL.- Zone names come from
pg_timezone_names, not abbreviations. - Day-based reports convert to the local zone before
date_trunc. - Range filters use
>=on the start and<on the end, with boundaries computed as instants.
Exercise
A table has created_at timestamp NOT NULL, and you know the application always wrote UTC values into it. Write the statement that converts the column to the correct type without changing the instants it represents, and explain why the USING clause is needed.
Show answer
ALTER TABLE t ALTER COLUMN createdat TYPE timestamptz USING createdat AT TIME ZONE 'UTC'; The USING clause tells PostgreSQL to read the stored plain values as UTC. Without it, the values would be interpreted in the session TimeZone, which could shift every instant by the session's offset.
Exercise
Why is it wrong to store the recurring meeting "every Monday at 09:00 Europe/Paris" as a list of precomputed UTC timestamps, and what should you store instead?
Show answer
After a DST change in Paris, 09:00 local corresponds to a different UTC time, and the DST rules themselves can change. Precomputed UTC instants would drift away from 09:00 local. Store the local wall-clock time (a plain timestamp, or a date plus a time) and the zone name (for example in a column with a foreign key to a zone table), then compute the instant with AT TIME ZONE when you need it.
Exercise
Write a WHERE clause that selects rows from event whose starts_at falls on 2024-11-03 in America/NewYork, a 25-hour day, and keeps an index on `startsat` usable.
Show answer
WHERE startsat >= TIMESTAMP '2024-11-03 00:00:00' AT TIME ZONE 'America/NewYork' AND startsat < TIMESTAMP '2024-11-04 00:00:00' AT TIME ZONE 'America/NewYork'. Both boundaries are local midnights converted to instants, so the 25-hour length is handled, and the column is compared directly so a B-tree index applies.