Sub topic 2
Converting with AT TIME ZONE
This chapter assumes you know basic SQL (SELECT, WHERE, GROUP BY), can run queries in psql, and understand UTC and UTC offsets.
Converting with AT TIME ZONE
The AT TIME ZONE operator converts between a zone-aware value and a wall-clock value. The result type depends on the input type:
| Input type | Result type | Meaning |
|---|---|---|
| timestamptz | timestamp | The wall-clock time in the named zone |
| timestamp | timestamptz | The wall-clock time, read as a time in the named zone |
SET TimeZone = 'UTC';
SELECT TIMESTAMPTZ '2024-06-01 07:00:00+00' AT TIME ZONE 'Asia/Tokyo';
-- 2024-06-01 16:00:00
SELECT TIMESTAMP '2024-06-01 09:00:00' AT TIME ZONE 'Europe/Paris';
-- 2024-06-01 07:00:00+00Predict the result type before you run each query.
> Note: the callout below is a fenced block, not a quote.
Getting the current time
now()returns the transaction start time. It stays the same for the whole transaction.clock_timestamp()returns the time at the moment of the call, so it can change within one statement.current_datereturns the date in the session TimeZone.
Working with intervals
An interval stores months, days, and seconds separately. This matters because a month has no fixed length.
SELECT interval '1 month' AS one_month, interval '24 hours' AS one_day_of_hours;Adding and subtracting dates and timestamps
Adding a month clamps to the last day of a shorter month. Adding interval '1 day' keeps the local clock time. Adding interval '24 hours' adds exactly 24 elapsed hours. The two differ across a daylight saving change.
SET TimeZone = 'America/New_York';
SELECT TIMESTAMPTZ '2024-03-09 12:00:00' + interval '1 day' AS plus_one_day,
TIMESTAMPTZ '2024-03-09 12:00:00' + interval '24 hours' AS plus_24_hours;
-- plus_one_day: 2024-03-10 12:00:00-04
-- plus_24_hours: 2024-03-10 13:00:00-04
SELECT date '2024-01-31' + interval '1 month' AS month_end_add;
-- 2024-02-29Extracting fields and truncating with date_trunc
extract returns one field as a number. date_trunc rounds a value down to a unit, which is useful for grouping. Convert to the local zone first so that days match local calendar days.
SELECT extract(epoch FROM TIMESTAMPTZ '2024-01-01 00:00:00+00') AS epoch_seconds;
-- 1704067200
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 query assumes an event table with a starts_at timestamptz column. On PostgreSQL 12 and later, date_trunc('day', starts_at, 'America/New_York') also works and returns a timestamptz.
Exercise
What type does SELECT TIMESTAMP '2024-06-01 09:00:00' AT TIME ZONE 'Europe/Paris' return, and what value does it show when the session TimeZone is UTC?
Show answer
It returns timestamptz, displayed as 2024-06-01 07:00:00+00, because Paris is UTC+02:00 in June.