TExcelTAD
Home › PostgreSQL › PostgreSQL Date & Time

PostgreSQL Date & Time

Dates and times are everywhere in business data: when a customer joined, when an order shipped, how long delivery took. PostgreSQL has excellent date/time support. This lesson uses fixed dates so every result is reproducible; in real applications you would often compare with current_date or now().

Getting the current date and time

Expression Returns
current_date today's date
now() / current_timestamp the start time of the current transaction (timestamptz)
localtimestamp the same without time zone
clock_timestamp() the real clock, changes during a statement
sql
SELECT current_date, now();   -- changes on every run, so not shown here

Building dates and timestamps

Write literals in ISO format, or build values from parts:

pgsql · try it yourself
SELECT DATE '2024-05-15'                          AS literal,
       make_date(2024, 2, 29)                     AS from_parts,
       make_timestamp(2024, 5, 15, 9, 30, 0)      AS ts,
       to_date('15/05/2024', 'DD/MM/YYYY')        AS parsed,
       '2024-05-15 18:45'::timestamp              AS cast_ts;
  literal   | from_parts |         ts          |   parsed   |       cast_ts
------------+------------+---------------------+------------+---------------------
 2024-05-15 | 2024-02-29 | 2024-05-15 09:30:00 | 2024-05-15 | 2024-05-15 18:45:00
(1 row)

Date arithmetic

Adding an integer to a date adds days. Subtracting two dates gives the number of days. Intervals express other units:

pgsql · try it yourself
SELECT DATE '2024-01-31' + 7                       AS plus_week,
       DATE '2024-01-31' + INTERVAL '1 month'      AS plus_month,
       DATE '2024-12-25' - DATE '2024-05-15'        AS days_until_christmas,
       TIMESTAMP '2024-05-15 09:30' + INTERVAL '2 hours 15 minutes' AS later,
       age(DATE '2024-12-31', DATE '1990-07-04')   AS age;
 plus_week  |     plus_month      | days_until_christmas |        later        |           age
------------+---------------------+----------------------+---------------------+-------------------------
 2024-02-07 | 2024-02-29 00:00:00 |                  224 | 2024-05-15 11:45:00 | 34 years 5 mons 27 days
(1 row)

Adding a month to 31 January gives 29 February in a leap year, because PostgreSQL clamps to the last day of the month.

Extracting parts

extract(field FROM value) (or date_part) pulls out one component; date_trunc rounds down to the start of a unit, which is perfect for grouping:

pgsql · try it yourself
SELECT id, order_date,
       extract(YEAR FROM order_date)    AS year,
       extract(MONTH FROM order_date)   AS month,
       extract(ISODOW FROM order_date)  AS weekday_1_mon,
       date_trunc('month', order_date)::date AS month_start
FROM orders
WHERE id IN (1, 7, 13);
 id | order_date | year | month | weekday_1_mon | month_start
----+------------+------+-------+---------------+-------------
  1 | 2024-01-05 | 2024 |     1 |             5 | 2024-01-01
  7 | 2024-04-08 | 2024 |     4 |             1 | 2024-04-01
 13 | 2024-08-02 | 2024 |     8 |             5 | 2024-08-01
(3 rows)

Orders per quarter:

pgsql · try it yourself
SELECT extract(QUARTER FROM order_date) AS quarter, count(*) AS orders
FROM orders
GROUP BY quarter
ORDER BY quarter;
 quarter | orders
---------+--------
       1 |      6
       2 |      5
       3 |      4
       4 |      5
(4 rows)

Formatting with to_char

to_char(value, pattern) turns a date into text in any layout:

Pattern Meaning Example
YYYY, MM, DD year, month, day 2024, 05, 15
Mon, Month month name (short / padded full) May
Dy, Day weekday name Wed
HH24:MI hours and minutes 09:30
FM prefix remove padding FMDay
pgsql · try it yourself
SELECT to_char(DATE '2024-05-15', 'DD Mon YYYY')           AS short,
       to_char(DATE '2024-05-15', 'FMDay, FMDD FMMonth YYYY') AS long,
       to_char(TIMESTAMP '2024-05-15 09:05', 'HH24:MI')    AS time,
       to_char(DATE '2024-05-15', '"Week" IW')             AS iso_week;
    short    |          long          | time  | iso_week
-------------+------------------------+-------+----------
 15 May 2024 | Wednesday, 15 May 2024 | 09:05 | Week 20
(1 row)

Ranges of dates

generate_series works with timestamps and intervals, which makes calendars and gap-free reports easy. Every month of the first half of 2024 with its number of orders, including months with none:

pgsql · try it yourself
SELECT to_char(m, 'YYYY-MM') AS month, count(o.id) AS orders
FROM generate_series(TIMESTAMP '2024-01-01', TIMESTAMP '2024-06-01', INTERVAL '1 month') AS m
LEFT JOIN orders o ON date_trunc('month', o.order_date) = m
GROUP BY m
ORDER BY m;
  month  | orders
---------+--------
 2024-01 |      2
 2024-02 |      2
 2024-03 |      2
 2024-04 |      2
 2024-05 |      1
 2024-06 |      2
(6 rows)

Time zones

A timestamptz value is an absolute moment. How it is displayed depends on the session's TimeZone setting, and AT TIME ZONE converts between zones:

pgsql · try it yourself
SET TimeZone = 'UTC';
SELECT TIMESTAMPTZ '2024-05-15 12:00:00+00'                         AS utc,
       TIMESTAMPTZ '2024-05-15 12:00:00+00' AT TIME ZONE 'Asia/Tokyo' AS tokyo_local,
       TIMESTAMP '2024-05-15 09:00' AT TIME ZONE 'America/New_York'   AS ny_9am_in_utc;
SET
          utc           |     tokyo_local     |     ny_9am_in_utc
------------------------+---------------------+------------------------
 2024-05-15 12:00:00+00 | 2024-05-15 21:00:00 | 2024-05-15 13:00:00+00
(1 row)

Tip: Store moments as timestamptz and convert to the user's zone only for display. Store calendar days (birthdays, publication dates) as date.

Test yourself

What is DATE '2024-03-10' - DATE '2024-03-01'?

  1. '9 days' as text
  2. 9 (an integer number of days)
  3. An interval of 1 week
  4. An error

Which function rounds a timestamp down to the first day of its month?

  1. extract('month', ts)
  2. date_trunc('month', ts)
  3. to_char(ts, 'MM')
  4. round(ts)

Why avoid now() in examples whose output is saved?

  1. now() is deprecated
  2. Its value changes on every run
  3. It only works in psql
  4. It returns NULL