【问题标题】:PgSQL turning day-of-year back into datePgSQL 将一年中的某一天恢复为日期
【发布时间】:2013-04-13 08:43:25
【问题描述】:

我正在尝试确定如何在 PgSQL 中将一年中的某一天转回日期。当我这样做时

select date '2013-01-01' + interval '53 days'

我得到一个时间戳:

"2013-02-23 00:00:00"

那么当我执行以下任何操作时,怎么会发生

select extract(date from (date '2013-01-01' + interval '53 days'))

select extract(date from (select date '2013-01-01' + interval '53 days'))

我收到“错误:无法识别时间戳单位“日期””?除了为什么,我该怎么做,即只获取原始操作结果的日期部分?

【问题讨论】:

标签: postgresql date


【解决方案1】:

使用

select (date '2013-01-01' + interval '53 days')::date

select cast(date '2013-01-01' + interval '53 days' as date)

PostgreSQL's standard SQL function "extract()" 对时间戳进行操作,但是 a)“日期”不是 extract() 的有效参数,b)它返回子字段,而不是子字段的集合。从概念上讲,日期由三个子字段的集合组成:年、月和日。

select extract(year from current_timestamp),
       extract(month from current_timestamp),
       extract(day from current_timestamp),
       -- Concatenate and cast to type "date".
       (extract(year from current_timestamp) || '-' || 
       extract(month from current_timestamp) || '-' ||
       extract(day from current_timestamp))::date

【讨论】:

  • 好的,谢谢。这样可行。那么我的概念有什么问题呢?如果 date + interval 构造返回一个时间戳,为什么提取函数不会对其进行操作?
  • @Steve:扩大了答案。
猜你喜欢
  • 2014-08-03
  • 2021-02-06
  • 2016-02-04
  • 2021-03-07
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 2016-01-22
  • 2023-04-02
相关资源
最近更新 更多