Dates and times

Topic 4 of 5 in Working with values12 min readBeginnerFree course

Overview

Almost every business question has a time dimension: orders this month, customers who signed up last year, revenue per week, deliveries overdue by more than three days. PostgreSQL has excellent date and time support, and a few functions — extract, date_trunc, intervals and to_char — cover nearly everything you’ll need.

Working with dates and times. An order’s ordered_at value of 2026-11-20 20:20 sits on a timeline between 2026-11-01 and 2026-11-30; date_trunc(‘month’, ordered_at) moves it back to 2026-11-01 00:00:00. now() and current_date give the current timestamp and date. extract(year from ordered_at) gives 2026. ordered_at::date gives 2026-11-20. ordered_at + interval ‘7 days’ gives 2026-11-27 20:20:00. current_date - signup_date gives a number of days as an integer. age(timestamp ‘2026-12-04’, signup_date) gives ‘1 year 1 mon 1 day’. to_char(ordered_at, ‘DD Mon YYYY’) gives ‘20 Nov 2026’. A date is a day; a timestamp is a date plus a time; timestamptz is an exact moment, shown in your time zone.

The date and time types

Type Example Meaning
date 2026-12-04 a calendar day, no time
time 09:30:00 a time of day, no date
timestamp 2026-12-04 09:30:00 a date and time, with no time zone
timestamptz 2026-12-04 09:30:00+00 an exact moment in time, displayed in your session’s time zone
interval 3 days 04:00:00 a length of time

In Bean & Leaf, customers.signup_date is a date and orders.ordered_at is a timestamp. For new tables that record when something happened, timestamptz is usually the better choice — more on that at the end.

Write date and time literals as text in ISO format and PostgreSQL converts them; add the type name in front to be explicit:

SQL
SELECT date '2026-12-04'                  AS a_date,
       timestamp '2026-12-04 09:30'        AS a_timestamp,
       interval '1 day 2 hours'            AS an_interval,
       '2026-12-04'::date + 1              AS tomorrow;
Text
   a_date   |     a_timestamp     |  an_interval   |  tomorrow  
------------+---------------------+----------------+------------
 2026-12-04 | 2026-12-04 09:30:00 | 1 day 02:00:00 | 2026-12-05
(1 row)

The current date and time

SQL
SELECT current_date,        -- today's date
       now(),               -- the current moment (timestamptz)
       localtimestamp;      -- the current date and time, without a time zone

These change every time you run them, so the lessons use a fixed “today” of 4 December 2026 instead, written as date '2026-12-04'. In your own queries, replace it with current_date. Note that now() returns the time the current transaction started, so it stays the same throughout one transaction — usually what you want.

Extracting parts

extract(field FROM value) pulls out one part as a number:

SQL
SELECT id, ordered_at,
       extract(year  FROM ordered_at) AS year,
       extract(month FROM ordered_at) AS month,
       extract(day   FROM ordered_at) AS day,
       extract(hour  FROM ordered_at) AS hour,
       extract(isodow FROM ordered_at) AS weekday
FROM orders
WHERE id IN (1, 23);
Text
 id |     ordered_at      | year | month | day | hour | weekday 
----+---------------------+------+-------+-----+------+---------
  1 | 2026-01-05 09:14:00 | 2026 |     1 |   5 |    9 |       1
 23 | 2026-11-20 20:20:00 | 2026 |    11 |  20 |   20 |       5
(2 rows)

isodow numbers the days Monday = 1 to Sunday = 7 (plain dow uses Sunday = 0). Other useful fields are quarter, week, doy (day of the year) and epoch (seconds since 1970). You’ll also see the older spelling date_part('month', ordered_at).

Extracting works in WHERE, too — orders placed at the weekend:

SQL
SELECT id, ordered_at
FROM orders
WHERE extract(isodow FROM ordered_at) IN (6, 7);
Text
 id |     ordered_at      
----+---------------------
  5 | 2026-02-14 20:22:00
  9 | 2026-03-21 08:30:00
 10 | 2026-04-04 19:05:00
 11 | 2026-04-18 13:37:00
 12 | 2026-05-02 09:50:00
 14 | 2026-06-07 10:10:00
 19 | 2026-09-19 18:18:00
 20 | 2026-10-03 10:45:00
 22 | 2026-11-08 09:09:00
 24 | 2026-11-29 11:30:00
(10 rows)

Truncating to a period

date_trunc(unit, value) rounds a timestamp down to the start of its hour, day, week, month, quarter or year. It’s the workhorse of time-based reporting — later you’ll group by it to get monthly totals:

SQL
SELECT ordered_at,
       date_trunc('day', ordered_at)     AS day,
       date_trunc('week', ordered_at)    AS week,
       date_trunc('month', ordered_at)   AS month,
       date_trunc('quarter', ordered_at) AS quarter
FROM orders
WHERE id = 23;
Text
     ordered_at      |         day         |        week         |        month        |       quarter       
---------------------+---------------------+---------------------+---------------------+---------------------
 2026-11-20 20:20:00 | 2026-11-20 00:00:00 | 2026-11-16 00:00:00 | 2026-11-01 00:00:00 | 2026-10-01 00:00:00
(1 row)

Weeks start on Monday. Unlike extract(month …), which gives 11 for November of every year, date_trunc('month', …) keeps the year — so November 2026 and November 2027 stay separate.

Converting a timestamp to a date with ::date is a quick way to drop the time:

SQL
SELECT ordered_at, ordered_at::date AS order_day
FROM orders
WHERE id = 23;
Text
     ordered_at      | order_day  
---------------------+------------
 2026-11-20 20:20:00 | 2026-11-20
(1 row)

Date arithmetic

Add or subtract an interval to move a date or timestamp:

SQL
SELECT ordered_at,
       ordered_at + interval '7 days'    AS plus_week,
       ordered_at - interval '2 hours'   AS minus_2h,
       ordered_at + interval '1 month'   AS plus_month
FROM orders
WHERE id = 23;
Text
     ordered_at      |      plus_week      |      minus_2h       |     plus_month      
---------------------+---------------------+---------------------+---------------------
 2026-11-20 20:20:00 | 2026-11-27 20:20:00 | 2026-11-20 18:20:00 | 2026-12-20 20:20:00
(1 row)

Adding a whole number to a date adds days. Subtracting one date from another gives the number of days between them, as an integer; subtracting timestamps gives an interval:

SQL
SELECT first_name, signup_date,
       date '2026-12-04' - signup_date        AS days_as_customer,
       age(date '2026-12-04', signup_date)    AS age
FROM customers
WHERE id IN (1, 5, 10);
Text
 first_name | signup_date | days_as_customer |        age         
------------+-------------+------------------+--------------------
 Asha       | 2025-11-03  |              396 | 1 year 1 mon 1 day
 Elena      | 2026-02-05  |              302 | 9 mons 27 days
 Jack       | 2026-09-15  |               80 | 2 mons 19 days
(3 rows)

age() expresses the difference in years, months and days, the way a person would. Use the day count for calculations and sorting, and age for display.

Months have different lengths, and PostgreSQL handles the edge cases sensibly — adding a month to 31 January gives the last day of February:

SQL
SELECT date '2026-01-31' + interval '1 month' AS end_of_feb,
       date '2028-02-29' - interval '1 year'  AS leap_back;
Text
     end_of_feb      |      leap_back      
---------------------+---------------------
 2026-02-28 00:00:00 | 2027-02-28 00:00:00
(1 row)

Filtering on dates

As you learned in Filtering with WHERE, the reliable pattern for a period is a half-open range: on or after the start, before the next start. Orders in the last 30 days before 4 December:

SQL
SELECT id, ordered_at, status
FROM orders
WHERE ordered_at >= date '2026-12-04' - 30
  AND ordered_at <  date '2026-12-04'
ORDER BY ordered_at;
Text
 id |     ordered_at      | status  
----+---------------------+---------
 22 | 2026-11-08 09:09:00 | paid
 23 | 2026-11-20 20:20:00 | pending
 24 | 2026-11-29 11:30:00 | pending
(3 rows)

You could write WHERE date_trunc('month', ordered_at) = '2026-11-01' or WHERE extract(month FROM ordered_at) = 11, and on a small table it works. On a large one, wrapping the column in a function stops the database from using an index on ordered_at, so the range form is the professional habit.

Formatting dates for people

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

SQL
SELECT ordered_at,
       to_char(ordered_at, 'DD Mon YYYY')            AS short,
       to_char(ordered_at, 'FMDay, FMDD FMMonth YYYY') AS long,
       to_char(ordered_at, 'YYYY-"Q"Q')              AS quarter,
       to_char(ordered_at, 'HH12:MI AM')             AS clock
FROM orders
WHERE id = 23;
Text
     ordered_at      |    short    |           long           | quarter |  clock   
---------------------+-------------+--------------------------+---------+----------
 2026-11-20 20:20:00 | 20 Nov 2026 | Friday, 20 November 2026 | 2026-Q4 | 08:20 PM
(1 row)

Common pattern codes: YYYY year, MM month number, Mon/Month month name, DD day, Day weekday name, HH24/HH12 hour, MI minutes, Q quarter. FM (“fill mode”) removes the padding spaces that names are otherwise given, and text in double quotes is copied as-is.

The reverse — text to a date — uses to_date or to_timestamp with the same patterns: to_date('04/12/2026', 'DD/MM/YYYY').

As with numbers, format dates last. A formatted date is text: '20 Nov 2026' sorts after '03 Oct 2026' alphabetically but before it in time.

Time zones in one paragraph

A timestamp is just a date and a clock reading — “20:20 on 20 November” — with no idea where. A timestamptz stores an exact moment (internally in UTC) and displays it in your session’s time zone. If your customers or servers are in more than one time zone, store moments as timestamptz; you can then view them in any zone:

SQL
SELECT timestamptz '2026-11-20 20:20+00' AT TIME ZONE 'Asia/Kolkata'     AS in_pune,
       timestamptz '2026-11-20 20:20+00' AT TIME ZONE 'America/Chicago'  AS in_austin;
Text
       in_pune       |      in_austin      
---------------------+---------------------
 2026-11-21 01:50:00 | 2026-11-20 14:20:00
(1 row)

The same moment was 1:50 the next morning in Pune and 2:20 in the afternoon in Austin.

Other databases: date functions vary more than anything else in SQL. MySQL uses DATE_FORMAT, DATEDIFF and DATE_ADD; SQL Server uses DATEPART, DATEADD, DATEDIFF and FORMAT; SQLite stores dates as text and uses strftime. The ideas — extract, truncate, add intervals, format — are the same everywhere.

Exercise

September's deliveries

Bean & Leaf promises delivery within 5 days. For every order placed in September 2026, return its id, the order_day (the order's date without the time), the weekday it was placed on as a full day name without padding (for example Tuesday), and a deliver_by date 5 days after the order day — sorted by id. Filter with a half-open range on ordered_at. You should get orders 18 and 19.

SQL
SELECT id, ordered_at
FROM orders
WHERE ___
ORDER BY id;

Summary

  • date is a calendar day, timestamp is a date and time, timestamptz is an exact moment shown in your time zone, and interval is a length of time.
  • Write literals in ISO format: '2026-12-04' and '2026-12-04 09:30'.
  • extract(part FROM value) pulls out a year, month, day, hour or weekday; date_trunc('month', value) rounds down to the start of a period.
  • Adding an interval moves a date or time; subtracting two dates gives a number of days, and age() gives years, months and days.
  • to_char formats dates for display; keep the real date type for filtering, sorting and grouping.