【问题标题】:How to insert current datetime in postgresql insert query [duplicate]如何在postgresql插入查询中插入当前日期时间[重复]
【发布时间】:2016-11-09 17:53:55
【问题描述】:
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的插入查询中插入当前日期时间?

【问题讨论】:

  • 也许搜索CURRENT_TIMESTAMP或什至NOW()。前者至少有精确的论据。所以CURRENT_TIMESTAMP(3)将产生 3 个亚秒位数(毫秒分辨率)
  • ... 通过 SET DATESTYLE 进行格式化,例如。 at:in postgres, can you set the default formatting for a timestamp, by session or globally? 或在官方 postgres 文档中
  • timestamp 列确实不具有“格式”。您看到的任何格式都由您使用的 SQL 客户端应用。如果您想要不同的 display 格式,请更改 SQL 客户端的配置或使用正确的格式化函数。
  • 是的,它在 MySQL 上运行,但现在您希望它在 Postgresql 中运行,因此您需要在 Postgresql 手册中查找等效函数。

标签: postgresql datetime insert


【解决方案1】:

timestamp(或date 或time 列)没有有“格式”。

您看到的任何格式都由您使用的 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

【讨论】:

  • 如果我使用它,我会收到以下错误,因为我的日期是时间戳格式。 “createddate”列是没有时区的时间戳类型,但表达式是文本类型
  • @Shesha 不要在 insert 查询中使用它。在您的insert 中使用current_timestamp
【解决方案2】:

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

您也可以参考以下链接。

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 2016-03-28
      • 1970-01-01
      • 2012-02-23
      相关资源
      最近更新 更多