Sub topic 5
Controlling the session `TimeZone`
Assume you know SELECT, WHERE, and basic PostgreSQL types. You should also know that UTC is a global reference time and that a UTC offset describes the difference between a local clock and UTC.
Each PostgreSQL connection has a session setting named TimeZone. It tells PostgreSQL which zone to use when it:
- Displays a
timestamptzvalue. - Interprets a timestamp that has no explicit offset.
- Calculates values such as
current_dateandcurrent_time. - Converts between
timestampandtimestamptz.
The setting does not change the instant stored in a timestamptz column.
SHOW TimeZone;
SET TIME ZONE 'America/New_York';
SELECT
now() AS current_instant,
current_date AS local_date,
current_time AS local_time;SET TIME ZONE changes only the current database session. Other connections keep their own settings. You can also use the assignment form:
SET timezone = 'UTC';
SET timezone TO 'Europe/Paris';A named region, such as America/New_York, is usually safer than a fixed offset such as -05:00. A named region includes daylight saving rules. New York uses different offsets during the year, while -05:00 always means five hours behind UTC.
Displaying the same instant
PostgreSQL stores a timestamptz as an instant. When it sends that value to your SQL client, it renders the instant using the session TimeZone.
CREATE TEMP TABLE event (
name text NOT NULL,
starts_at timestamptz NOT NULL
);
INSERT INTO event (name, starts_at)
VALUES ('launch', '2024-06-01 09:00:00+02');
SET TIME ZONE 'America/New_York';
SELECT name, starts_at FROM event;
-- launch | 2024-06-01 03:00:00-04
SET TIME ZONE 'UTC';
SELECT name, starts_at FROM event;
-- launch | 2024-06-01 07:00:00+00Both queries return the same instant. Only its presentation changes. The offset shown in the result is the offset that applied in the selected zone at that instant.
Transaction-local settings
A connection pool may reuse sessions. A plain SET can therefore affect later work that uses the same connection. Use SET LOCAL when a setting should last only until the current transaction ends.
BEGIN;
SET LOCAL TIME ZONE 'Asia/Tokyo';
SELECT starts_at
FROM event;
COMMIT;
SHOW TIME ZONE;After COMMIT, the session returns to its previous TimeZone.
You can define defaults for a database or role, but an explicit session setting overrides them:
ALTER DATABASE reporting SET timezone = 'UTC';
ALTER ROLE analyst SET timezone = 'Europe/London';These commands affect future sessions, not transactions that are already connected.
Exercise
If the same timestamptz displays as 12:00 in UTC and 08:00 in America/New_York, did PostgreSQL store two different times?
Show answer
No. It stored one instant. The session TimeZone changed how PostgreSQL rendered that instant.