PostgreSQL – TO_TIMESTAMP Function

The TO_TIMESTAMP function is used to convert a string representation of a timestamp into a timestamp data type. It’s particularly useful when you have timestamp values stored as strings and you want to convert them into actual timestamp values for further manipulation or comparison.

The syntax of the TO_TIMESTAMP function is as follows:

TO_TIMESTAMP(string, format)

Here’s an example of using the TO_TIMESTAMP function to convert a string into a timestamp:

SELECT TO_TIMESTAMP('2023-08-12 15:30:00', 'YYYY-MM-DD HH24:MI:SS') AS converted_timestamp;

In this example, the string ‘2023-08-12 15:30:00’ is converted into a timestamp using the ‘YYYY-MM-DD HH24:MI:SS’ format.

You can also use the TO_TIMESTAMP function to handle timestamps with different formats:

SELECT TO_TIMESTAMP('12/Aug/2023 03:30 PM', 'DD/Mon/YYYY HH:MI AM') AS converted_timestamp;

In this example, the string ’12/Aug/2023 03:30 PM’ is converted into a timestamp using the ‘DD/Mon/YYYY HH:MI AM’ format.

The second argument of the TO_TIMESTAMP function (format) specifies the expected format of the input string so that PostgreSQL can correctly interpret and convert it into a timestamp.

The TO_TIMESTAMP function is particularly useful when dealing with data that’s stored as strings but needs to be treated as timestamps for various operations, such as date calculations, sorting, or filtering.

Similar Posts