如何在postgresql插入查询中插入当前日期时间

时间:2016-07-07 12:05:00

标签: postgresql datetime insert

INSERT into Group (Name,CreatedDate) VALUES ('Test',UTC_TIMESTAMP(), 1);

这是我用于mysql插入当前日期时间的查询。 当我在postgresql中使用它时,我遇到了错误。

    HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
********** Error **********

ERROR: function utc_timestamp() does not exist
SQL state: 42883

我尝试使用now()进行如下操作,但它的插入方式与"2016-07-07 17:01:18.410677"类似。我需要以'yyyymmdd hh:mi:ss tt'格式插入。

INSERT into Group (Name,CreatedDate) VALUES ('Test',UTC_TIMESTAMP(), 1);

如何以上述格式在postgresql的插入查询中插入当前日期时间?

3 个答案:

答案 0 :(得分:61)

timestamp(或datetime列) NOT 有"格式"。

您看到的任何格式都由您正在使用的SQL客户端应用。

要插入当前时间,请使用current_timestamp as documented in the manual

INSERT into "Group" (name,createddate) 
VALUES ('Test', current_timestamp);

显示以不同格式显示该值会更改SQL客户端的配置或在选择数据时格式化值:

select name, to_char(createddate, ''yyyymmdd hh:mi:ss tt') as created_date
from "Group"

对于psql(默认命令行客户端),您可以通过配置参数DateStyle配置显示格式:https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-DATESTYLE

答案 1 :(得分:2)

对于当前日期时间,您可以在postgresql插入查询中使用now()函数。

您也可以参考以下链接。

insert statement in postgres for data type timestamp without time zone NOT NULL,

答案 2 :(得分:0)

您当然可以格式化current_timestamp()的结果。 请查看官方documentation中的各种格式化功能。