PostgreSQL date_part Function: Extract Date Components
In this article
The PostgreSQL date_part function extracts specific parts of a date or timestamp, such as year, month, day, hour, or minute. It requires no special setup beyond having PostgreSQL installed and access to a database with date or timestamp data. This function is essential for time-based analysis, reporting, or filtering in SQL queries.
What You'll Need
- A working PostgreSQL server (version 9.0 or later)
- Access to a database containing at least one date, timestamp, or timestamptz column
- A SQL client such as psql, pgAdmin, DBeaver, or any tool that can execute SQL queries
- Basic familiarity with SQL syntax and table structures
Step-by-Step
- Connect to your PostgreSQL database using your preferred SQL client. For example, in psql, use
psql -U username -d database_nameand enter your password when prompted. - Identify the table and column containing date or timestamp data. Run
SELECT column_name FROM table_name LIMIT 1;to confirm the data type. The column must be of type DATE, TIMESTAMP, or TIMESTAMPTZ. - Use the
date_partfunction in a SELECT statement with two arguments: the part you want to extract (as a string), and the column or expression to extract it from. For example:SELECT date_part('year', created_at) FROM orders;This returns the year from each timestamp in thecreated_atcolumn. - Extract multiple date parts in a single query by calling
date_partmultiple times. For example:SELECT date_part('year', created_at) AS year, date_part('month', created_at) AS month, date_part('day', created_at) AS day FROM orders;This returns three separate columns with the respective date components. - Use
date_partwith expressions, not just columns. For example:SELECT date_part('hour', now() - interval '3 hours');This calculates the hour part of three hours ago from the current time. - Combine
date_partwith WHERE clauses to filter results. For example:SELECT * FROM events WHERE date_part('month', event_date) = 12;This returns all events that occurred in December. - Use
date_partwith ORDER BY to sort results by extracted components. For example:SELECT * FROM sales ORDER BY date_part('day', sale_time);This sorts sales by the day of the month, regardless of the year or month. - Test with different time units by replacing the first argument with any valid part:
'year','month','day','hour','minute','second','quarter','week','dow'(day of week, 0=Sunday),'doy'(day of year),'epoch'(seconds since Unix epoch). - For time zones, use
TIMESTAMPTZcolumns. The function automatically adjusts to the timezone of the timestamp. For example:SELECT date_part('hour', '2023-12-25 14:30:00-05'::timestamptz);returns 14, even if your session timezone is UTC.
Common Mistakes
- Using single quotes around the part name incorrectly:
date_part(year, created_at)will fail. Always use single quotes:'year'. - Confusing
date_partwithextract, which does the same thing but has different syntax. While both work,date_partis more explicit and widely supported across SQL dialects. - Using invalid part names like
'minuteofhour'or'weekofmonth'. Only the standard parts listed in the PostgreSQL documentation are valid. - Passing a string literal that isn’t a valid date or timestamp. For example:
date_part('year', 'not a date')will throw an error. Always ensure the input is a proper date type. - Assuming
date_partworks on INTERVAL types. It does not. To extract from intervals, useextractinstead.
Tips
- Use
date_part('epoch', timestamp)to convert timestamps to Unix seconds, useful for calculations in applications or APIs. - When writing reports, combine
date_partwithGROUP BYto aggregate by month:SELECT date_part('month', created_at), COUNT(*) FROM orders GROUP BY 1 ORDER BY 1; - For readability, alias the result with AS:
date_part('day', created_at) AS day_of_monthmakes output easier to understand. - Use
date_part('dow', timestamp)to find weekend records:WHERE date_part('dow', event_time) IN (0, 6)finds Sundays and Saturdays. - When comparing months across years, use
date_part('month', timestamp)with caution — it ignores the year. Combine with year if needed:WHERE date_part('year', timestamp) = 2023 AND date_part('month', timestamp) = 12. - For performance, avoid applying
date_parton indexed date columns in WHERE clauses. Instead, use date ranges:WHERE created_at >= '2024-01-01' AND created_at < '2024-02-01'to leverage index scans.
Troubleshooting
- If you get an error like
function date_part(unknown, timestamp) does not exist, check that the first argument is enclosed in single quotes. Double quotes or no quotes cause this. - If the result is NULL, verify the column contains valid data. Run
SELECT column_name IS NULL FROM table_name LIMIT 5;to check for null values. - If you get
invalid input syntax for type timestamp, the input expression is not a valid date. UseCAST('2023-12-01' AS TIMESTAMP)to explicitly convert strings. - If the time component is off by hours, check your session timezone with
SHOW timezone;. UseSET timezone TO 'UTC';to standardize if needed. - If the query runs slowly on large tables, avoid using
date_partin WHERE clauses. Instead, rewrite filters using date ranges or create a functional index:CREATE INDEX idx_order_month ON orders (date_part('month', created_at)); - If you’re using pgAdmin and see an error that doesn’t appear in psql, check for hidden characters or encoding issues in your query editor. Copy the query into a plain text editor and retype it.
Frequently Asked Questions
Can date_part extract milliseconds?
No. The date_part function does not support milliseconds. Use extract(epoch from timestamp) * 1000 to get milliseconds since epoch, or use EXTRACT(MILLISECONDS FROM timestamp) instead.
Does date_part work with interval data types?
No. date_part only works with date and timestamp types. For intervals, use the EXTRACT function, which supports components like hours, minutes, and seconds from intervals.
What is the difference between date_part and extract?
They are functionally identical in PostgreSQL. EXTRACT is SQL-standard syntax; date_part is PostgreSQL-specific. Both return the same result. Use whichever your team prefers for consistency.
Can I use date_part to find the last day of the month?
No. date_part returns components like day, not the total days in a month. Use date_trunc('month', date) + interval '1 month - 1 day' to compute the last day.
Why does date_part('dow', '2024-01-01') return 1 when January 1, 2024, is a Monday?
PostgreSQL’s dow returns 0 for Sunday, 1 for Monday, up to 6 for Saturday. So Monday = 1 is correct. This matches ISO 8601 standards.
Can date_part handle time zones automatically?
Yes, when used with TIMESTAMPTZ, it converts the timestamp to the session’s time zone before extraction. If you need UTC, set SET timezone TO 'UTC'; before running the query.