postgresql中的日期差异

Posted

技术标签:

【中文标题】postgresql中的日期差异【英文标题】:Date difference in days in postgresql 【发布时间】:2019-06-18 21:25:06 【问题描述】:

我正在尝试以天为单位计算日期之间的差异。 列 snapshot_date 和 date_opened 的数据类型是 Text。我收到一个错误:函数 date_part(unknown, integer) 不存在

SELECT DATE_PART('day', snapshot_date::date -date_opened::date)::number from my_table

【问题讨论】:

查看类似线程***.com/questions/17833176/… "datatype is Text for columns snapshot_date 和 date_opened" -- 修复此问题并使用日期类型,如 datetimestamp 你的 postgreSQL 版本是多少? 从不将日期值存储在text(或varchar)列中。这样做是一个非常非常糟糕的主意。 【参考方案1】:

As documented in the manual从另一个日期中减去一个日期返回一个表示天数的整数,所以:

snapshot_date::date - date_opened::date

就是你所需要的。

这假设两列都可以安全地转换为date

【讨论】:

以上是关于postgresql中的日期差异的主要内容,如果未能解决你的问题,请参考以下文章