Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL date_part Function: Extract Date Components

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. Connect to your PostgreSQL database using your preferred SQL client. For example, in psql, use psql -U username -d database_name and enter your password when prompted.
  2. 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.
  3. Use the date_part function 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 the created_at column.
  4. Extract multiple date parts in a single query by calling date_part multiple 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.
  5. Use date_part with 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.
  6. Combine date_part with 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.
  7. Use date_part with 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.
  8. 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).
  9. For time zones, use TIMESTAMPTZ columns. 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_part with extract, which does the same thing but has different syntax. While both work, date_part is 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_part works on INTERVAL types. It does not. To extract from intervals, use extract instead.

Tips

  • Use date_part('epoch', timestamp) to convert timestamps to Unix seconds, useful for calculations in applications or APIs.
  • When writing reports, combine date_part with GROUP BY to 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_month makes 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_part on 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. Use CAST('2023-12-01' AS TIMESTAMP) to explicitly convert strings.
  • If the time component is off by hours, check your session timezone with SHOW timezone;. Use SET timezone TO 'UTC'; to standardize if needed.
  • If the query runs slowly on large tables, avoid using date_part in 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.