Date and Time Functions in PostgreSQL

PostgreSQL, an open-source object-relational database system, provides a plethora of functionalities, including powerful date and time functions that are useful in many real-world situations. These functions are particularly handy when we're dealing with data that requires time stamp manipulation, scheduling events, or analyzing data over time. This blog post aims to provide an introductory yet comprehensive guide on how to use these date and time functions in PostgreSQL. By the end, you should be able to understand and apply these functions to manipulate and analyze time-series data efficiently.

Introduction to Date and Time Functions in PostgreSQL

Understanding PostgreSQL Date and Time Types

Before diving into the functions, let's briefly understand the date and time types that PostgreSQL provides. There are primarily four types that we should be aware of:

  • DATE: Stores the date only (YYYY-MM-DD)
  • TIME: Stores the time of day only (HH:MI:SS)
  • TIMESTAMP: Stores the date and time (YYYY-MM-DD HH:MI:SS)
  • INTERVAL: Represents a span of time (quantified in terms of days, hours, minutes, etc.)
CREATE TABLE demo( date_col DATE, time_col TIME, timestamp_col TIMESTAMP, interval_col INTERVAL );

In the example above, we created a table named demo with columns of each date and time type.

Basic Date and Time Functions

Now let's discuss some of the basic functions available:

  • NOW(): This function returns the current date and time as a TIMESTAMP.

  • CURRENT_DATE: Returns the current date as a DATE type.

  • CURRENT_TIME: Returns the current time as a TIME type.

  • EXTRACT(field FROM source): Extracts and returns the value of a specified field from a date, time, or interval source. 'Field' could be year, month, day, hour, minute, second, etc.

  • AGE(timestamp, timestamp): Calculates the difference between two timestamps and returns it as an INTERVAL.

    SELECT AGE(TIMESTAMP '2023-05-19', TIMESTAMP '2020-05-19');

Working with Date and Time Arithmetic

PostgreSQL allows for date and time arithmetic, which can be incredibly useful when calculating deadlines, estimating dates, or generating reports based on dates.

Let's understand this with the help of examples:

  • Adding an interval to a DATE or TIMESTAMP

    SELECT NOW() + INTERVAL '1 day';
  • Subtracting two DATES or TIMESTAMPS

    SELECT TIMESTAMP '2023-05-19' - TIMESTAMP '2020-05-19';
  • Subtracting an INTERVAL from a DATE or TIMESTAMP

    SELECT NOW() - INTERVAL '1 day';

Advanced Date and Time Functions

Beyond these basic functionalities, PostgreSQL offers several other date and time functions that might be useful:

  • TO_CHAR(date, format): This function converts a date, time, or timestamp to a string according to a specified format.

  • TO_DATE(string, format): This function converts a string to a date based on a specified format.

    SELECT TO_DATE('19-05-2023', 'DD-MM-YYYY');
  • DATE_TRUNC(field,source): This function truncates a TIMESTAMP to a specified precision. This is very useful when grouping data by a specific time unit.

  • INTERVAL 'value': Creates an interval value that can be used to add or subtract from DATEs and TIMESTAMPs.

    SELECT NOW() + INTERVAL '1 year 2 months 3 days';

Date and Time Functions in Conditions and Filtering

You can also use date and time functions in WHERE clauses to filter results:

SELECT * FROM orders WHERE DATE_TRUNC('day', order_date) = CURRENT_DATE;

In the example above, we return all rows from the orders table where the order_date is the current date.

Frequently Asked Questions (FAQ)

Q1: How to add/subtract days to a date in PostgreSQL?

A1: You can add or subtract days to a date using the INTERVAL keyword as shown below:

SELECT CURRENT_DATE + INTERVAL '1 day'; -- Add 1 day SELECT CURRENT_DATE - INTERVAL '1 day'; -- Subtract 1 day

Q2: How to extract the month from a date in PostgreSQL?

A2: You can extract the month from a date using the EXTRACT function. Here's how:


Q3: How to convert a string to a date or timestamp in PostgreSQL?

A3: You can use the TO_DATE function to convert a string to a date. Similarly, the TO_TIMESTAMP function is used to convert a string to a timestamp.

SELECT TO_DATE('19-05-2023', 'DD-MM-YYYY'); -- Convert string to date SELECT TO_TIMESTAMP('19-05-2023 12:00:00', 'DD-MM-YYYY HH24:MI:SS'); -- Convert string to timestamp

Q4: How to get the difference between two dates in PostgreSQL?

A4: The AGE function provides the difference between two dates or timestamps in PostgreSQL.

SELECT AGE(TIMESTAMP '2023-05-19', TIMESTAMP '2020-05-19');

The PostgreSQL date and time functions are powerful tools for manipulating and querying date and time values. Their versatility and flexibility make them an essential part of every PostgreSQL user's toolkit. Whether you're calculating time intervals, formatting date and time values, or extracting specific components from a timestamp, these functions can help you accomplish your goals. With practice and careful study, you'll become proficient at using these functions to handle your date and time-related tasks in PostgreSQL.

Sharing is caring

Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.


No comments so far

Leave a question/feedback and someone will get back to you