Cal11 calculator

Postgres Calculate Time Interval

Reviewed by Calculator Editorial Team

Calculating time intervals in PostgreSQL is essential for database operations, reporting, and business logic. This guide explains how to work with time intervals using PostgreSQL functions and provides a practical calculator to compute intervals between timestamps.

What is a Time Interval?

A time interval represents the duration between two points in time. In PostgreSQL, time intervals can be calculated using timestamps, dates, and time values. Common interval units include seconds, minutes, hours, days, months, and years.

Time intervals are crucial for:

  • Calculating durations between events
  • Scheduling and time-based triggers
  • Age calculations for records
  • Time-based aggregations in reports

PostgreSQL Time Functions

PostgreSQL provides several functions to work with time intervals:

Key Time Functions

  • NOW() - Returns current timestamp
  • CURRENT_DATE - Returns current date
  • AGE(timestamp1, timestamp2) - Calculates interval between two timestamps
  • EXTRACT(field FROM interval) - Extracts specific parts of an interval
  • INTERVAL 'value unit' - Creates an interval value

These functions allow you to perform complex time calculations directly in your database queries.

Calculating Time Intervals

The basic syntax for calculating time intervals in PostgreSQL is:

Time Interval Calculation

SELECT timestamp1 - timestamp2 AS interval;

This returns the interval between two timestamps as a PostgreSQL interval type.

For example, to calculate the interval between two timestamps:

Example Calculation

SELECT '2023-12-31 23:59:59'::timestamp - '2023-01-01 00:00:00'::timestamp AS interval;

This would return an interval of approximately 364 days, 23 hours, 59 minutes, and 59 seconds.

You can also extract specific parts of an interval using the EXTRACT function:

Extracting Interval Parts

SELECT EXTRACT(DAY FROM interval) AS days;

This extracts just the day component from an interval.

Common Use Cases

Time interval calculations are used in various scenarios:

Use Case PostgreSQL Function Example
Calculate age of records AGE() SELECT AGE(NOW(), created_at) FROM users;
Find duration between events - operator SELECT end_time - start_time FROM events;
Schedule recurring events INTERVAL SELECT NOW() + INTERVAL '1 month' AS next_due;

FAQ

How do I calculate the difference between two timestamps in PostgreSQL?
Use the subtraction operator between two timestamp values. For example: SELECT timestamp1 - timestamp2; This returns the interval between the two timestamps.
Can I extract specific parts of a time interval?
Yes, use the EXTRACT function. For example: SELECT EXTRACT(DAY FROM interval_value); This extracts just the day component from an interval.
How do I calculate someone's age in PostgreSQL?
Use the AGE function: SELECT AGE(NOW(), birth_date) FROM users; This returns the interval between the current date and the birth date.