Sub topic 1
The date and time types and when to use each
Prerequisites
This chapter assumes you can run basic SQL (CREATE TABLE, INSERT, SELECT) in psql or another client. You should also know what UTC is and what a UTC offset such as +02 means.
The five types
PostgreSQL has five main types for time data:
datestores a calendar day with no time of day.timestores a time of day with no date.timestampstores a date and time with no time zone.timestamptzstores a date and time that refers to one exact instant. The name means "timestamp with time zone."intervalstores a length of time, such as "3 days" or "2 hours".
Choose the type by asking what the value means. A birthday is a date. A store's opening time is a time. A moment that happened once, such as a payment, is a timestamptz.
CREATE TABLE sample (
birthday date,
opens_at time,
logged_at timestamp,
paid_at timestamptz,
duration interval
);Writing date and time literals
A literal is a value written directly in SQL. Use the ISO 8601 format, YYYY-MM-DD HH:MI:SS. It is unambiguous across locales. Add an offset to a timestamptz literal, such as '2024-06-01 09:00:00+02', or use Z for UTC.
The DateStyle setting controls how dates are displayed. It does not change the stored value.
What timestamptz really stores
A timestamptz value does not keep the offset you typed. PostgreSQL converts the input to UTC and stores that instant. When you read the value, PostgreSQL converts it to the session's time zone for display. Two inputs with different offsets that describe the same instant are stored as the same value.
Time zone names, abbreviations, and offsets
You can name a zone in three ways:
- Full IANA names, such as
'America/New_York'. These follow daylight saving time (DST) rules and are the safest choice. - Abbreviations, such as
'EST'. These are fixed offsets and ignore DST. - Fixed offsets, such as
'+02'. These never change.
Prefer full IANA names in application code.
Controlling the session TimeZone
The TimeZone setting controls how timestamptz values are displayed in your session:
SET TimeZone = 'America/New_York';
SELECT TIMESTAMPTZ '2024-06-01 07:00:00+00'; -- 2024-06-01 03:00:00-04The stored instant is the same. Only the display changes.
Exercise
Exercise
A meeting is stored as timestamptz. A user in Tokyo and a user in Paris both query it. Why do they see different clock times, and does the stored value differ?
Show answer
The stored value is identical, because timestamptz keeps one UTC instant. Each session displays that instant in its own TimeZone setting, so Tokyo and Paris show different wall-clock times.