Sub topic 7
Dates, times, timestamps and intervals
This chapter assumes you know basic SELECT, INSERT, and CREATE TABLE, and that you can run queries in PostgreSQL. PostgreSQL provides separate types for calendar dates, clock times, moments in time, and lengths of time. Choosing the correct type prevents timezone and arithmetic errors.
The main date and time types
| Type | Represents | Example |
|---|---|---|
| `date` | A calendar date without a time | `2026-01-15` |
| `time` | A time of day without a date | `09:30:00` |
| `timestamp` | A date and time without timezone handling | `2026-01-15 09:30:00` |
| `timestamptz` | An absolute moment in time | `2026-01-15 09:30:00+00` |
| `interval` | A duration or calendar span | `2 hours`, `3 months` |
PostgreSQL calls timestamp with time zone by the short name timestamptz. It stores an instant, not the timezone label that was entered. PostgreSQL converts the value to the current session timezone when it displays it.
CREATE TABLE appointments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
meeting_date date NOT NULL,
starts_at timestamptz NOT NULL,
duration interval NOT NULL,
CHECK (duration > interval '0 seconds')
);
INSERT INTO appointments (meeting_date, starts_at, duration)
VALUES (
DATE '2026-01-15',
TIMESTAMPTZ '2026-01-15 12:00:00+00',
INTERVAL '90 minutes'
);
SELECT
meeting_date,
starts_at,
starts_at + duration AS ends_at
FROM appointments;`timestamp` versus `timestamptz`
Use timestamptz for an event that occurs at one global moment, such as a payment, login, or shipment. Use timestamp when the value is intentionally a wall-clock reading with no location, such as “the store opens at 09:00” or a recurring local schedule.
SET TIME ZONE 'America/New_York';
SELECT
TIMESTAMPTZ '2026-01-15 12:00:00+00' AS instant,
TIMESTAMPTZ '2026-01-15 12:00:00+00'
AT TIME ZONE 'America/New_York' AS new_york_time;The first result is displayed in the session timezone. The AT TIME ZONE expression converts the instant to a timestamp showing the local wall-clock time.
Date and interval arithmetic
Adding an interval to a date or timestamp produces a new date or timestamp. Subtracting two timestamps produces an interval. Subtracting two dates produces an integer number of days.
SELECT
DATE '2026-01-31' + INTERVAL '1 month' AS one_month_later,
DATE '2026-01-15' + 10 AS ten_days_later,
TIMESTAMP '2026-01-15 09:00:00'
- TIMESTAMP '2026-01-14 17:30:00' AS elapsed;Intervals can contain months, days, and clock time. A month is calendar-based, so adding one month to January 31 does not mean adding a fixed number of seconds. Test boundary cases when business rules depend on month ends.
Exercise
Which type should store the instant when a customer placed an order, and which type should store a store's daily opening time of 09:00?
Show answer
Use timestamptz for the order instant. Use timestamp, or time if only the clock time is needed, for the opening schedule.