Sub topic 3
Formatting and parsing text
This chapter assumes you know basic SQL, can run queries in psql, and understand UTC and offsets such as +02.
Formatting and parsing text
Use to_char to turn a timestamp into text, and to_timestamp to read text into a timestamptz. Both use format patterns such as YYYY, MM, DD, HH24, MI, and TZ.
SET TimeZone = 'UTC';
SELECT to_char(TIMESTAMPTZ '2024-06-01 07:00:00+00', 'YYYY-MM-DD HH24:MI TZ');
-- 2024-06-01 07:00 UTC
SELECT to_timestamp('2024-06-01 09:00', 'YYYY-MM-DD HH24:MI');
-- 2024-06-01 09:00:00+00to_timestamp without an offset in the text uses the session TimeZone. Include an offset when the input comes from another zone. to_date returns a date with no time part.
Querying time ranges with half-open intervals
Use >= on the start and < on the end. A row stamped exactly at midnight on July 1 belongs to July, so it is not counted twice or missed.
SELECT *
FROM event
WHERE starts_at >= TIMESTAMPTZ '2024-06-01 00:00:00+00'
AND starts_at < TIMESTAMPTZ '2024-07-01 00:00:00+00';Daylight saving time pitfalls
Adding interval '1 day' keeps the local clock time. Adding interval '24 hours' adds 24 elapsed hours. On 2024-03-10 in New York, clocks jump forward, so the two results differ.
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;
-- 2024-03-10 12:00:00-04 | 2024-03-10 13:00:00-04Use day units when you mean a calendar day, and hour units when you mean elapsed time.
Generating time series and using range types
generate_series produces one row per step. Stepping by one day from midnight avoids the 2 a.m. switch. A tstzrange stores an interval as one value, and @> tests whether a value falls inside it.
SET TimeZone = 'America/New_York';
SELECT generate_series(TIMESTAMPTZ '2024-03-09 00:00:00',
TIMESTAMPTZ '2024-03-11 00:00:00',
interval '1 day') AS day_start;
-- 2024-03-09 00:00:00-05
-- 2024-03-10 00:00:00-04
-- 2024-03-11 00:00:00-04
SELECT tstzrange(TIMESTAMPTZ '2024-06-01 00:00+00',
TIMESTAMPTZ '2024-07-01 00:00+00', '[)')
@> TIMESTAMPTZ '2024-06-15 12:00+00' AS in_june;
-- trueGuidelines for time zone safe schemas
- Store event times as
timestamptz. - Store the user's zone name, such as
America/New_York, in its own column when local rules matter. - Convert to local time only at display or grouping, using
AT TIME ZONE. - Build ranges with half-open bounds.
- Avoid storing local wall-clock times without a zone.
Exercise
Exercise
With TimeZone set to 'Asia/Tokyo', what does SELECT to_char(TIMESTAMPTZ '2024-06-01 07:00:00+00', 'HH24:MI'); return?
Show answer
16:00. to_char formats the value in the session zone. Tokyo is UTC+9, so 07:00 UTC becomes 16:00.