Sub topic 6
Converting with `AT TIME ZONE`
This chapter assumes basic SELECT and WHERE queries, familiarity with psql or another SQL client, and a general idea of UTC and UTC offsets.
PostgreSQL uses AT TIME ZONE for two related conversions. The direction depends on the value's type:
timestamptotimestamptz: interpret a clock reading in a named time zone.timestamptztotimestamp: display an instant as a clock reading in a named time zone.
The result type changes in each direction.
Interpreting a local time
A timestamp has a date and clock time but no time zone. For example, 09:00 could mean 09:00 in Paris, New York, or Tokyo. AT TIME ZONE supplies the missing interpretation.
-- The local time is 09:00 in Paris.
SELECT TIMESTAMP '2024-06-01 09:00:00'
AT TIME ZONE 'Europe/Paris' AS instant;
-- 2024-06-01 07:00:00+00 when the session zone is UTCThe result is a timestamptz. PostgreSQL represents the same instant internally regardless of the session's display zone. The named zone is used only to interpret the input clock reading.
This is useful when an application receives a scheduled local time and also knows the intended location. Store the resulting timestamptz when the event represents one specific instant.
Displaying an instant in a local zone
A timestamptz identifies an instant. Applying AT TIME ZONE to it produces a timestamp showing the local wall-clock time in the requested zone.
SET TimeZone = 'UTC';
SELECT TIMESTAMPTZ '2024-06-01 07:00:00+00'
AT TIME ZONE 'Asia/Tokyo' AS tokyo_time;
-- 2024-06-01 16:00:00The result has no time zone attached. It is a calendar reading for presentation, reporting, or further local-calendar calculations. Do not store this result as if it still identified a unique instant.
Use named zones
Prefer IANA names such as Europe/Paris, America/New_York, and Asia/Tokyo. They include daylight saving rules. A fixed offset such as +02 does not describe future seasonal changes.
Applying the conversion to a column
Suppose starts_at is a timestamptz column. Grouping by the UTC date can differ from grouping by the New York calendar date.
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;Here, the conversion happens before truncation. PostgreSQL first turns each instant into a New York wall-clock timestamp, then date_trunc keeps the local day.
Exercise
What type does TIMESTAMP '2024-06-01 09:00:00' AT TIME ZONE 'Europe/Paris' return, and what does the zone mean?
Show answer
It returns timestamptz. The expression interprets 09:00 as a local Paris time and converts it to the corresponding instant.