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 < on the raw column.
timestamp or timestamptz?
PostgreSQL has two types for a date with a time. timestamp (timestamp without time zone) stores the value as is, like MySQL's DATETIME. timestamptz (timestamp with time zone) converts the value to UTC on write and displays it in the session time zone (timezone setting) on read, like MySQL's TIMESTAMP, but from 4713 BC to year 294276. Neither stores the original time zone. The PostgreSQL wiki recommends timestamptz for points in time (creation, order, log); I use timestamp in this article so that results do not depend on the session time zone, except in the time zone part.
Get the current date and time
now() (or current_timestamp) returns a timestamptz, current_date and current_time return only one part, and localtimestamp returns a timestamp without time zone.
SET timezone = 'Europe/Paris'; SELECT now(), current_date, current_time, localtimestamp; now | current_date | current_time | localtimestamp -------------------------------+--------------+--------------------+---------------------------- 2026-11-07 19:25:54.991767+01 | 2026-11-07 | 19:25:54.991767+01 | 2026-11-07 19:25:54.991767
Beware, now() is fixed at the start of the transaction, not of the statement as in MySQL. statement_timestamp() gives the start of the statement, and clock_timestamp() the actual time, which moves on even during the statement:
BEGIN; SELECT now(), statement_timestamp(), clock_timestamp(), pg_sleep(2), clock_timestamp(); now | statement_timestamp | clock_timestamp | pg_sleep | clock_timestamp -------------------------------+-------------------------------+-------------------------------+----------+------------------------------- 2026-11-07 19:25:54.991929+01 | 2026-11-07 19:25:54.991967+01 | 2026-11-07 19:25:54.992115+01 | | 2026-11-07 19:25:56.994225+01 SELECT now(), statement_timestamp(); now | statement_timestamp -------------------------------+------------------------------- 2026-11-07 19:25:54.991929+01 | 2026-11-07 19:25:56.994603+01 COMMIT;
In the second statement, now() did not move: in a long transaction, all rows inserted with DEFAULT now() get the same date.
Extract part of a date
A cast is enough to split the date and the time; EXTRACT() returns each field as a number.
SELECT ts, ts::date AS day, ts::time AS time, EXTRACT(YEAR FROM ts) AS year, EXTRACT(MONTH FROM ts) AS month, EXTRACT(DAY FROM ts) AS day_of_month, EXTRACT(HOUR FROM ts) AS h, EXTRACT(MINUTE FROM ts) AS min, EXTRACT(SECOND FROM ts) AS sec FROM ma_table; ts | day | time | year | month | day_of_month | h | min | sec ---------------------+------------+----------+------+-------+--------------+----+-----+----------- 2012-09-01 16:00:30 | 2012-09-01 | 16:00:30 | 2012 | 9 | 1 | 16 | 0 | 30.000000
Since PostgreSQL 14, EXTRACT() returns a numeric, hence the decimals on the seconds. date_part('year', ts) does the same and returns a double precision.
date_trunc() has no direct equivalent in MySQL and is used all the time: it truncates a date to the given unit. It is the ideal tool to group by month, week or hour.
SELECT ts, date_trunc('month', ts) AS month, date_trunc('hour', ts) AS hour, date_trunc('week', ts) AS week FROM ma_table; ts | month | hour | week ---------------------+---------------------+---------------------+--------------------- 2012-09-01 16:00:30 | 2012-09-01 00:00:00 | 2012-09-01 16:00:00 | 2012-08-27 00:00:00
The week starts on Monday (ISO standard). Calendar fields are also available with EXTRACT():
SELECT ts, to_char(ts, 'Day') AS day_name, EXTRACT(DOW FROM ts) AS dow, EXTRACT(ISODOW FROM ts) AS isodow, EXTRACT(WEEK FROM ts) AS week, EXTRACT(QUARTER FROM ts) AS quarter, EXTRACT(DOY FROM ts) AS day_of_year, (date_trunc('month', ts) + interval '1 month - 1 day')::date AS last_day FROM ma_table; ts | day_name | dow | isodow | week | quarter | day_of_year | last_day ---------------------+-----------+-----+--------+------+---------+-------------+------------ 2012-09-01 16:00:30 | Saturday | 6 | 6 | 35 | 3 | 245 | 2012-09-30
DOW goes from 0 (Sunday) to 6, ISODOW from 1 (Monday) to 7 (Sunday). Unlike MySQL, EXTRACT(WEEK ...) is always the ISO 8601 week: 2027-01-01 is in week 53 of ISO year 2026. To display both together, use to_char(ts, 'IYYY-IW'), never 'YYYY-IW'.
SELECT EXTRACT(WEEK FROM date '2027-01-01') AS week, EXTRACT(ISOYEAR FROM date '2027-01-01') AS iso_year, to_char(date '2027-01-01', 'IYYY-IW') AS iso; week | iso_year | iso ------+----------+--------- 53 | 2026 | 2026-53
There is no LAST_DAY() function: the last day of the month is the first day of the month, plus one month, minus one day, as in the previous query.
Format a date
to_char() plays the role of MySQL's DATE_FORMAT(), with different patterns: no %, but uppercase keywords.
SELECT ts, to_char(ts, 'YYYY Month DD') AS long, to_char(ts, 'FMMM/FMDD/YY HH12:MI:SS AM') AS short, to_char(ts, 'DD/MM/YYYY HH24:MI') AS european FROM ma_table; ts | long | short | european ---------------------+-------------------+--------------------+------------------ 2012-09-01 16:00:30 | 2012 September 01 | 9/1/12 04:00:30 PM | 01/09/2012 16:00
Day and month names are padded with spaces to 9 characters ('Saturday '); the FM prefix removes this padding and leading zeros. The most useful patterns:
| Pattern | Meaning | Example | MySQL equivalent |
|---|---|---|---|
YYYY / YY | Year, 4 or 2 digits | 2012 / 12 | %Y / %y |
MM / FMMM | Month, with or without leading zero | 09 / 9 | %m / %c |
Month / Mon | Month name, full or short | September / Sep | %M / %b |
DD / FMDD | Day of the month, with or without leading zero | 01 / 1 | %d / %e |
Day / Dy | Day name, full or short | Saturday / Sat | %W / %a |
HH24 / HH12 | Hour, 24 or 12 hours | 16 / 04 | %H / %h |
MI / SS | Minutes / seconds | 00 / 30 | %i / %s |
AM | AM or PM | PM | %p |
IYYY-IW | ISO 8601 year and week | 2012-35 | %x-%v |
Watch out for the classic trap: MM is the month, MI the minutes. To get names in another language, add the TM prefix and set lc_time. The locale must be installed on the server, otherwise PostgreSQL rejects the value.
SET lc_time = 'fr_FR.UTF-8'; SELECT to_char(ts, 'TMDay DD TMMonth YYYY') AS with_tm, to_char(ts, 'Day DD Month YYYY') AS without_tm FROM ma_table; with_tm | without_tm --------------------------+----------------------------- Samedi 01 Septembre 2012 | Saturday 01 September 2012
Add or subtract an interval
No need for DATE_ADD(): you add an interval directly, written in plain words and combinable.
SELECT ts, ts + interval '5 days' AS plus_5_days, ts + interval '1 year 10 months' AS plus_1_year_10_months, ts + interval '1 month' + interval '10 days' AS plus_1_month_10_days FROM ma_table; ts | plus_5_days | plus_1_year_10_months | plus_1_month_10_days ---------------------+---------------------+-----------------------+---------------------- 2012-09-01 16:00:30 | 2012-09-06 16:00:30 | 2014-07-01 16:00:30 | 2012-10-11 16:00:30
To subtract, same principle. On a date, an integer is a number of days. make_interval() builds an interval from parameters, handy when the value comes from a column or a query parameter.
SELECT ts, ts - interval '2 hours' AS minus_2_hours, ts::date - 10 AS minus_10_days, ts - make_interval(weeks => 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 < '2025-01-01'; QUERY PLAN ------------------------------------------------------------------------------------------ Bitmap Heap Scan on orders (cost=715.91..2300.57 rows=33511 width=4) Recheck Cond: ((created_at >= '2024-01-01 00:00:00'::timestamp without time zone) AND (created_at < '2025-01-01 00:00:00'::timestamp without time zone)) -> 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 < '2025-01-01 00:00:00'::timestamp without time zone))
Same trap with BETWEEN '2024-01-01' AND '2024-12-31' on a timestamp: the upper bound means 2024-12-31 00:00:00, so the whole last day is forgotten. On a test table with a row at 2024-12-31 23:59:59, BETWEEN returns 2 rows where >= ... < returns 3.
If you always filter by month, PostgreSQL also allows an expression index:
CREATE INDEX idx_orders_month ON orders (date_trunc('month', created_at)); EXPLAIN SELECT id FROM orders WHERE date_trunc('month', created_at) = '2024-06-01'; QUERY PLAN ------------------------------------------------------------------------------------------------------------------ Bitmap Heap Scan on orders (cost=37.51..1168.30 rows=3253 width=4) Recheck Cond: (date_trunc('month'::text, created_at) = '2024-06-01 00:00:00'::timestamp without time zone) -> 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