简体   繁体   中英

How to Convert to Datetime YYYY-MM-DD HH:mi:ss

I have a field where I need to populate GETDATE() with YYYY-MM-DD HH-MI-SS format.

Can anyone help me how to write the query in PostgreSQL?

I tried this in SQL Server and it worked. Not sure how to write in PostgreSQL.

SELECT
    SUBSTRING(CONVERT(VARCHAR(23),GETDATE(),112),1,4) + '-' +
    SUBSTRING(CONVERT(VARCHAR(23),getdate(),112),5,2) + '-' +
    SUBSTRING(CONVERT(VARCHAR(23),getdate(),112),7,2) + ' ' +
    CONVERT(VARCHAR(8), GETDATE(), 108)

Your help is appreciated. Thank You Swathi.

Using NOW() with TO_CHAR() should do that for you:

SELECT TO_CHAR(NOW(),'YYYY-MM-DD HH-MI-SS');

Docs: https://www.postgresql.org/docs/9.5/static/functions-formatting.html


To add some additional clarity...

You have a table with a field that is of a datetime type. When you update the field, you must update it with a value of the same type.

If you want to return the values in that field in a particular format, you would use the TO_CHAR() in your SELECT statement.

For example:

DROP TABLE IF EXISTS mytable;
CREATE TABLE mytable (mydate TIMESTAMP);
INSERT INTO mytable VALUES (NOW() - INTERVAL '20 days');

-- Update with the appropriate type
UPDATE mytable SET mydate = NOW();

-- Select the date in the format you want
SELECT mydate, TO_CHAR(mydate,'YYYY-MM-DD HH-MI-SS') AS mydate_text FROM mytable;

OUTPUT:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM