PostgreSQL – How to Convert Timestamp to String

You can convert a timestamp to a string in PostgreSQL database using the TO_CHAR function, which allows you to format the timestamp as a string with a specific format. Here’s how you can do it:

SELECT TO_CHAR(your_timestamp_column, 'YYYY-MM-DD HH24:MI:SS') AS timestamp_string FROM your_table;

where

  • your_timestamp_column is the name of the timestamp column you want to convert to a string.
  • your_table is the name of the table where the timestamp column resides.

The format string 'YYYY-MM-DD HH24:MI:SS' specifies the desired format for the resulting string. You can customize the format to meet your requirements. In this example, the format represents the year (YYYY), month (MM), day (DD), hour (HH24), minute (MI), and second (SS) components of the timestamp, separated by hyphens, colons, and spaces.

For instance, if you want to convert a timestamp to just a date or just a time, you can adjust the format string accordingly. Here are a few examples:

Convert date only:

SELECT transaction_date, TO_CHAR(transaction_date, 'YYYY-MM-DD') AS date_string FROM sales;

Convert time only:

SELECT TO_CHAR(current_timestamp, 'HH24:MI:SS') AS time_string;

You can modify the format string as needed to get the desired representation of the timestamp as a string.

Similar Posts