Handling dates and times in SQL queries with PostgreSQL
Handling dates and times in SQL queries with PostgreSQL
This article is the PostgreSQL counterpart of handling dates and times with MySQL & MariaDB. The needs are the same: get the current date, extract a part, format, add an interval, compute a difference, convert, and filter on a date range without breaking the index.
But PostgreSQL answers them differently: few dedicated functions, and many operators on the date, timestamp and interval types. All examples use a timestamp column named ts. Tested with PostgreSQL 18 (November 2026).
TL;DR
now() gives the transaction start time, clock_timestamp() the actual time; EXTRACT() and date_trunc() extract or truncate a date; to_char() formats it; you add an interval with + interval '5 days'; subtracting two dates gives an interval (or a number of days between two date values); to_date(), to_timestamp() and AT TIME ZONE convert. To filter a period, use >= and 1) AS minus_1_week FROM ma_table;
ts | minus_2_hours | minus_10_days | minus_1_week
---------------------+---------------------+---------------+---------------------
2012-09-01 16:00:30 | 2012-09-01 14:00:30 | 2012-08-22 | 2012-08-25 16:00:30
Like MySQL, PostgreSQL falls back to the last day of the month when the target day does not exist. As a consequence, adding one month twice does not give the same result as adding two months.
SELECT date '2024-01-31' + interval '1 month' AS a, date '2023-01-31' + interval '1 month' AS b, date '2024-02-29' + interval '1 year' AS c;
a | b | c
---------------------+---------------------+---------------------
2024-02-29 00:00:00 | 2023-02-28 00:00:00 | 2025-02-28 00:00:00
SELECT date '2024-01-31' + interval '1 month' + interval '1 month' AS twice, date '2024-01-31' + interval '2 months' AS at_once;
twice | at_once
---------------------+---------------------
2024-03-29 00:00:00 | 2024-03-31 00:00:00
On a timestamptz, interval '1 day' and interval '24 hours' are not equivalent. A day follows the calendar of the session time zone, hours are actual hours. The difference shows when switching to daylight saving time:
SET timezone = 'Europe/Paris';
SELECT timestamptz '2024-03-30 12:00:00' + interval '1 day' AS plus_1_day, timestamptz '2024-03-30 12:00:00' + interval '24 hours' AS plus_24_hours;
plus_1_day | plus_24_hours
------------------------+------------------------
2024-03-31 12:00:00+02 | 2024-03-31 13:00:00+02
Since PostgreSQL 16, date_add(ts, interval, 'Europe/Paris') does the same calculation in a given time zone, whatever the session one.
Difference between two dates
There is no DATEDIFF() nor TIMESTAMPDIFF(): you subtract. Two timestamp values give an interval, two date values give a number of days.
SELECT timestamp '2012-12-31 12:36:00' - timestamp '2012-12-25 23:59:00' AS difference, date '2012-12-31' - date '2012-12-25' AS days;
difference | days
-----------------+------
5 days 12:37:00 | 6
To get the difference in another unit, extract the number of seconds with EXTRACT(EPOCH FROM ...) and divide:
SELECT EXTRACT(EPOCH FROM timestamp '2012-12-31 12:36:00' - timestamp '2012-12-25 23:59:00') / 60 AS minutes;
minutes
-----------------------
7957.0000000000000000
For years and months, use age(), which returns a "symbolic" interval in years, months and days. It is the right function to compute an age:
SELECT age(date '2026-11-07', date '1990-11-08') AS age, EXTRACT(YEAR FROM age(date '2026-11-07', date '1990-11-08')) AS years;
age | years
--------------------------+-------
35 years 11 mons 29 days | 35
As with DATEDIFF() in MySQL, the difference between two date values counts calendar days, while the difference between two timestamp values counts the actual duration:
SELECT timestamp '2024-01-02 00:30:00'::date - timestamp '2024-01-01 23:30:00'::date AS calendar_days, timestamp '2024-01-02 00:30:00' - timestamp '2024-01-01 23:30:00' AS duration;
calendar_days | duration
---------------+----------
1 | 01:00:00
Convert a date
A string in ISO format converts with a simple cast. For another format, to_date() and to_timestamp() take the pattern as a parameter, with the same patterns as to_char().
SELECT CAST('2012-12-25' AS timestamp) AS iso, to_date('25/12/2012', 'DD/MM/YYYY') AS to_date, to_timestamp('25/12/2012 14:30', 'DD/MM/YYYY HH24:MI')::timestamp AS to_ts;
iso | to_date | to_ts
---------------------+------------+---------------------
2012-12-25 00:00:00 | 2012-12-25 | 2012-12-25 14:30:00
Where MySQL returns NULL with a warning, PostgreSQL raises an error on a date it cannot read. The cast depends on the DateStyle setting (ISO, MDY by default): '25/12/2012' is read as the 12th day of the 25th month.
SELECT CAST('25/12/2012' AS date);
ERROR: date/time field value out of range: "25/12/2012"
HINT: Perhaps you need a different "DateStyle" setting.
SET datestyle = 'ISO, DMY';
SELECT CAST('25/12/2012' AS date) AS dmy;
dmy
------------
2012-12-25
Better not to depend on this setting and use the explicit to_date().
To exchange dates with an application, EXTRACT(EPOCH FROM ...) gives the Unix timestamp and to_timestamp(number) does the opposite, returning a timestamptz.
SET timezone = 'UTC';
SELECT EXTRACT(EPOCH FROM timestamptz '2012-09-01 16:00:30+00') AS epoch, to_timestamp(1346515230) AS from_epoch;
epoch | from_epoch
-------------------+------------------------
1346515230.000000 | 2012-09-01 16:00:30+00
Finally, AT TIME ZONE replaces MySQL's CONVERT_TZ(), with a subtlety: applied to a timestamp, it states in which time zone the value is expressed and returns a timestamptz; applied to a timestamptz, it returns the local time in the requested time zone. Hence the double conversion to go from UTC to Paris. Named time zones are built into PostgreSQL: nothing to load, unlike MySQL.
SELECT timestamp '2012-09-01 16:00:30' AT TIME ZONE 'UTC' AT TIME ZONE 'Europe/Paris' AS paris, timestamptz '2012-09-01 16:00:30+00' AT TIME ZONE 'America/New_York' AS new_york;
paris | new_york
---------------------+---------------------
2012-09-01 18:00:30 | 2012-09-01 12:00:30
Generate a series of dates
generate_series() produces one row per day, week or month between two dates. Useful to fill a calendar, or for a monthly report that must show months without data:
SELECT jour::date AS day FROM generate_series(timestamp '2012-09-01', timestamp '2012-09-03', interval '1 day') AS jour;
day
------------
2012-09-01
2012-09-02
2012-09-03
SELECT m::date AS month, count(o.ts) AS total FROM generate_series(timestamp '2012-09-01', timestamp '2012-11-01', interval '1 month') AS m LEFT JOIN (VALUES (timestamp '2012-09-01 16:00:30'), ('2012-09-15 10:00'), ('2012-11-02 08:00')) AS o(ts) ON date_trunc('month', o.ts) = m GROUP BY m ORDER BY m;
month | total
------------+-------
2012-09-01 | 2
2012-10-01 | 0
2012-11-01 | 1
A simple GROUP BY date_trunc('month', ts) would not have shown October.
Filter on a period without breaking the index
As in MySQL, WHERE EXTRACT(YEAR FROM created_at) = 2024 returns the right rows but prevents the use of the index on created_at. On a 200,000-row table, PostgreSQL scans the whole table:
EXPLAIN SELECT id FROM orders WHERE EXTRACT(YEAR FROM created_at) = 2024;
QUERY PLAN
--------------------------------------------------------------------------
Gather (cost=1000.00..3946.71 rows=1000 width=4)
Workers Planned: 1
-> Parallel Seq Scan on orders (cost=0.00..2846.71 rows=588 width=4)
Filter: (EXTRACT(year FROM created_at) = '2024'::numeric)
EXPLAIN SELECT id FROM orders WHERE created_at >= '2024-01-01' AND created_at = '2024-01-01 00:00:00'::timestamp without time zone) AND (created_at
Bitmap Index Scan on idx_orders_created (cost=0.00..707.53 rows=33511 width=0)
Index Cond: ((created_at >= '2024-01-01 00:00:00'::timestamp without time zone) AND (created_at = ...
Bitmap Index Scan on idx_orders_month (cost=0.00..36.69 rows=3253 width=0)
Index Cond: (date_trunc('month'::text, created_at) = '2024-06-01 00:00:00'::timestamp without time zone)
On a timestamptz column, this index is rejected (functions in index expression must be marked IMMUTABLE), because the result depends on the session time zone. You then have to specify the time zone: date_trunc('month', created_at, 'Europe/Paris').
MySQL / PostgreSQL equivalents
| MySQL / MariaDB | PostgreSQL |
|---|---|
NOW() |
now() (transaction start) or statement_timestamp() |
SYSDATE() |
clock_timestamp() |
UTC_TIMESTAMP() |
now() AT TIME ZONE 'UTC' |
YEAR(ts), MONTH(ts) ... |
EXTRACT(YEAR FROM ts) ... |
DATE(ts) |
ts::date |
LAST_DAY(ts) |
(date_trunc('month', ts) + interval '1 month - 1 day')::date |
DATE_FORMAT(ts, '%d/%m/%Y') |
to_char(ts, 'DD/MM/YYYY') |
DATE_ADD(ts, INTERVAL 5 DAY) |
ts + interval '5 days' |
DATEDIFF(d1, d2) |
d1::date - d2::date |
TIMESTAMPDIFF(MINUTE, d1, d2) |
EXTRACT(EPOCH FROM d2 - d1) / 60 |
TIMESTAMPDIFF(YEAR, d1, d2) |
EXTRACT(YEAR FROM age(d2, d1)) |
STR_TO_DATE(s, '%d/%m/%Y') |
to_date(s, 'DD/MM/YYYY') |
UNIX_TIMESTAMP(ts) |
EXTRACT(EPOCH FROM ts) |
FROM_UNIXTIME(n) |
to_timestamp(n) |
CONVERT_TZ(ts, 'UTC', 'Europe/Paris') |
ts AT TIME ZONE 'UTC' AT TIME ZONE 'Europe/Paris' |
FAQ
How do I get yesterday's date in PostgreSQL?
current_date - 1 for the date, now() - interval '1 day' for the date and time.
How do I get the first and last day of the month?
date_trunc('month', ts) gives the first day, (date_trunc('month', ts) + interval '1 month - 1 day')::date the last one.
How do I compute an age in years?
EXTRACT(YEAR FROM age(current_date, birth_date)): age() counts full years, so the birthday must have passed.
Why does now() always return the same time in my transaction?
Because now() is fixed at the start of the transaction. Use clock_timestamp() for the actual time, or statement_timestamp() for the start of each statement.
To choose how to store dates, most arguments of which format to use to store dates with MySQL / MariaDB also apply to PostgreSQL. To read an execution plan, see how to use EXPLAIN to optimize a query (written for MySQL, the approach is the same). Official documentation: date/time functions and operators, data type formatting functions and date/time types of PostgreSQL 18.
Add a comment
Comments
No comments yet. Start the discussion.