1/22/2024 0 Comments Postgresql cast date to stringFor this purpose, we will use the TO_CHAR() function as follows: SELECT a_title, p_date, TO_CHAR(p_date, 'YYYY/MM/DD HH:MM:SS') AS publised_date Let’s say we need to convert the “p-date” column into a string type. The output snippet shows that the “p_date” column has a TIMESTAMP data type. Now execute the “ SELECT *” query to fetch all the records of the “article_information” table. ('How to Delete Duplicates in Postgres', ' 11:10:50'), ('How to Count Unique Values in Postgres', ' 09:00:00'), Now, execute the INSERT INTO command to insert some records into the newly created table: INSERT INTO article_information(a_title, p_date) The table named “article_information” has been successfully created via the CREATE TABLE command. The “ a_id” column will accept numeric data, the “ a_title” column will accept the textual data, and the “ p_date” column will accept the TIMESTAMP values: The output snippet shows that the specified timestamp was successfully converted into the string.Įxample 2: How to Convert a TIMESTAMP Column to a String in Postgres?įirst, let’s create a sample table with three columns: a_id, a_name, and p_date: CREATE TABLE article_information( On successful execution of the TO_CHAR() function, the current date and time will be converted into a string: In this example, we will pass the CURRENT_TIMESTAMP function as the first argument and a valid format as a second argument to the TO_CHAR() function: SELECT TO_CHAR(CURRENT_TIMESTAMP, 'YYYY/MM/DD HH12:MM:SS') While the ‘formatMask’ parameter represents a valid timestamp format as described in the official Postgres documentation.Įxample: How to Convert a CURRENT_TIMESTAMP to a String in Postgres? In place of the “timestamp_expression” parameter, you can specify a timestamp column or any built-in date time function like NOW(), CURRENT_TIMESTAMP, etc. To do that, the TO_CHAR() function takes two arguments: a timestamp and a format string specifying how the timestamp should be formatted as a string: TO_CHAR(timestamp_expression, formatMask) In Postgres, a built-in conversion function named TO_CHAR() is used to convert the given timestamp to a string. How Do I Convert a TIMESTAMP to a String in Postgres? This write-up will teach you how to use the TO_CHAR() function to convert a timestamp into a string in Postgres. The format mask must be a valid number or date. The TO_CHAR() function utilizes a format mask to convert the input value to a string. PostgreSQL allows us to convert a date, interval, number, timestamp, etc., to a string via the TO_CHAR() function.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |