Sub topic 10
Extracting Fields and Truncating with date_trunc
This chapter covers extract, date_part, and date_trunc. These are the standard tools for answering questions like "which hour of the day?" and "which local day or month does this row belong to?". It assumes you know the difference between timestamp and timestamptz, that you know the session TimeZone setting controls how timestamptz is displayed, and that you can use AT TIME ZONE.
Two jobs: pulling a field out and rounding down
The two jobs are easy to confuse because both look at parts of a timestamp.
extractanddate_partreturn a number, such as the hour, the month, or the day of the week.date_truncreturns a timestamp rounded down to the start of a unit, such as the start of the day or month.
Use extract for questions about a recurring position ("which hour of the day is busiest?"). Use date_trunc for questions about a specific period ("how many events happened in each calendar month?").
extract and date_part
extract(field FROM source) is the SQL-standard form. date_part('field', source) is the older PostgreSQL form. They read the same fields. The difference is the return type. Since PostgreSQL 14, extract returns numeric. date_part returns double precision, and so did extract before version 14.
SET TimeZone = 'UTC';
SELECT extract(year FROM ts) AS year,
extract(month FROM ts) AS month,
extract(day FROM ts) AS day,
extract(hour FROM ts) AS hour,
extract(second FROM ts) AS second,
extract(isodow FROM ts) AS isodow,
extract(doy FROM ts) AS doy,
extract(week FROM ts) AS iso_week,
extract(isoyear FROM ts) AS isoyear
FROM (SELECT TIMESTAMPTZ '2024-12-30 22:15:30.5+00' AS ts) AS t;
-- year=2024 month=12 day=30 hour=22 second=30.500000
-- isodow=1 doy=365 iso_week=1 isoyear=2025Some fields need care:
| Field | Meaning | Gotcha |
|---|---|---|
| `second` | Seconds including the fraction | Returns `30.500000`, not `30`. |
| `dow` | Day of week, 0 = Sunday to 6 = Saturday | Differs from `isodow`. |
| `isodow` | Day of week, 1 = Monday to 7 = Sunday | Usually the less surprising choice. |
| `week` | ISO 8601 week number | Can belong to the neighboring year. |
| `isoyear` | The year that owns the ISO week | Pair it with `week`, never with `year`. |
| `epoch` | Seconds since 1970-01-01 00:00:00 UTC | For plain `timestamp`, the value is not zone-adjusted. |
The example shows the week trap. 2024-12-30 is in ISO week 1 of 2025, so year says 2024 and isoyear says 2025. A report that groups by year and week will put the last days of December into the wrong bucket.
extract on timestamptz uses the session zone
For a timestamptz, the fields are computed in the session TimeZone. The same instant gives different answers in different sessions:
SET TimeZone = 'Asia/Tokyo';
SELECT extract(hour FROM TIMESTAMPTZ '2024-12-30 22:15:30.5+00') AS hour,
extract(day FROM TIMESTAMPTZ '2024-12-30 22:15:30.5+00') AS day,
extract(timezone FROM TIMESTAMPTZ '2024-12-30 22:15:30.5+00') AS offset_seconds;
-- hour=7 day=31 offset_seconds=32400If you want the hour in a specific zone no matter who runs the query, convert explicitly: extract(hour FROM starts_at AT TIME ZONE 'America/New_York'). That expression is a plain timestamp, so session settings no longer affect it.
extract on intervals
On an interval, fields are read from the stored parts. They are not recomputed into larger units.
SELECT extract(hour FROM interval '2 days 3 hours') AS hours_part,
extract(month FROM interval '14 months') AS months_part,
extract(epoch FROM interval '1 day') AS total_seconds;
-- hours_part=3 months_part=2 total_seconds=86400hour is 3, not 51, because days are stored separately. For a total duration, use epoch and divide. Be aware that epoch on an interval treats a month as 30 days and a day as 24 hours.
date_trunc
date_trunc(field, source [, time_zone]) rounds down to the start of the unit named by field. The valid units are microseconds, milliseconds, second, minute, hour, day, week, month, quarter, year, decade, century, and millennium.
The result has the same type as the input. A timestamp gives a timestamp, a timestamptz gives a timestamptz, and an interval gives an interval. A date argument is cast to timestamptz first. That cast means the session zone applies to it, and the result has a zone.
Truncating timestamptz depends on the zone
For a timestamptz, "start of day" means midnight in the session zone, not midnight UTC. Take an event at 03:30 UTC on 1 June. In New York it is still the evening of 31 May. The following query shows four ways of truncating it:
SET TimeZone = 'UTC';
SELECT ts AS instant,
date_trunc('day', ts) AS utc_day,
date_trunc('day', ts, 'America/New_York') AS ny_day_start,
date_trunc('day', ts AT TIME ZONE 'America/New_York') AS ny_local_day
FROM (SELECT TIMESTAMPTZ '2024-06-01 03:30:00+00' AS ts) AS t;
-- instant 2024-06-01 03:30:00+00
-- utc_day 2024-06-01 00:00:00+00
-- ny_day_start 2024-05-31 04:00:00+00
-- ny_local_day 2024-05-31 00:00:00The last two columns describe the same New York day, but they have different types. ny_day_start is a timestamptz, the instant when that local day began. It is displayed as 04:00 UTC because New York is UTC-4 in June. ny_local_day is a plain timestamp holding the wall-clock label 2024-05-31 00:00:00.
Use the AT TIME ZONE form when you group and want readable day labels. Use the three-argument form (PostgreSQL 12 and later) when you need the actual boundary instant, for example to build a range filter.
Weeks, quarters, and the Monday rule
date_trunc('week', ...) always rounds down to Monday, following ISO 8601. If your business week starts on Sunday, shift before and after:
SELECT date_trunc('week', TIMESTAMP '2024-06-02 10:00') AS monday_week,
date_trunc('week', TIMESTAMP '2024-06-02 10:00' + interval '1 day')
- interval '1 day' AS sunday_week;
-- monday_week 2024-05-27 00:00:00
-- sunday_week 2024-06-02 00:00:002024-06-02 is a Sunday, so the ISO week starts on 27 May. Adding a day pushes the Sunday into the following Monday's week, and subtracting a day moves the result back.
Days are not always 24 hours
Truncation happens in the zone, and zones have daylight saving changes. In New York on 2024-03-10, clocks jump from 02:00 to 03:00:
SET TimeZone = 'America/New_York';
WITH t AS (SELECT date_trunc('day', TIMESTAMPTZ '2024-03-10 15:00:00-04') AS d)
SELECT d AS day_start,
d + interval '1 day' AS next_day_start,
(d + interval '1 day') - d AS length
FROM t;
-- day_start 2024-03-10 00:00:00-05
-- next_day_start 2024-03-11 00:00:00-04
-- length 23:00:00The day starts at UTC-5 and the next one at UTC-4, so the day is 23 hours long. Never assume 86400 seconds per day when you aggregate over local days.
Grouping with extract and date_trunc
The most common mistake is grouping by extract(month FROM ts) when the data spans several years. January 2023 and January 2024 land in the same group. Use date_trunc('month', ...) to keep periods distinct. Reserve extract for cases where merging across periods is the point, like a histogram of events by hour of day:
-- Events by local hour of day, merged across all dates
SELECT extract(hour FROM starts_at AT TIME ZONE 'America/New_York') AS local_hour,
count(*) AS events
FROM event
GROUP BY 1
ORDER BY 1;
-- Events per local month, kept distinct across years
SELECT date_trunc('month', starts_at AT TIME ZONE 'America/New_York') AS local_month,
count(*) AS events
FROM event
GROUP BY 1
ORDER BY 1;Indexing a truncated expression
date_trunc('day', starts_at) on a timestamptz depends on the session TimeZone, so PostgreSQL treats it as stable, not immutable, and refuses it in an index. Converting with a fixed zone name first produces a timestamp, and that expression can be indexed:
CREATE INDEX event_ny_day_idx
ON event (date_trunc('day', starts_at AT TIME ZONE 'America/New_York'));A query uses this index only if it repeats the same expression. Truncating in the WHERE clause also stops a plain index on starts_at from being used. For a single range, a half-open filter on the raw column (covered in a later chapter) is usually faster.
Common errors
- Reading
extractordate_truncon atimestamptzand getting a different answer in another session. Fix: convert withAT TIME ZONE, or pass the zone todate_trunc. - Grouping by
extract(week ...)withextract(year ...). Fix: useisoyearwithweek, or usedate_trunc('week', ...). - Expecting
dowto start on Monday.dowstarts on Sunday at 0. Useisodowfor Monday = 1. - Casting
extracttointfor display and losing the fraction ofsecond. Fix: usefloor, or truncate tosecondfirst.
Exercise
The session TimeZone is 'UTC'. A row has starts_at = '2024-11-03 02:30:00+00' (a timestamptz). You want to count rows per New York calendar day and show a plain date label. Write the expression for the grouping column, and say which local day this row falls in.
Show answer
Use datetrunc('day', startsat AT TIME ZONE 'America/New_York'). The instant 02:30 UTC is 22:30 on 2 November in New York (UTC-4 at that time, since daylight saving ends later that morning), so the row is counted in the local day 2024-11-02. The result is a plain timestamp, 2024-11-02 00:00:00.
Exercise
What do extract(hour FROM interval '1 day 5 hours') and extract(epoch FROM interval '1 day 5 hours') return, and why do they differ so much?
Show answer
The first returns 5 and the second returns 104400. An interval stores months, days, and time separately. extract(hour ...) reads only the time part, which is 5 hours. extract(epoch ...) converts the whole interval to seconds, treating a day as 24 hours: 29 hours is 104400 seconds.
Exercise
A report groups sales with extract(month FROM sold_at) and shows only 12 rows even though the table covers three years. What is wrong, and what is the fix?
Show answer
extract(month ...) returns only the month number 1 to 12, so the same month from different years is merged into one group. Group by datetrunc('month', soldat), converting with AT TIME ZONE first if sold_at is a timestamptz and the report needs a specific zone.