[英]Extracting number of months from an interval
What am I doing wrong? 我究竟做错了什么?
SELECT DATE_PART('month', '2018-05-31'::timestamp - '2018-02-24'::timestamp);
It returns 0! 它返回0! All the time.
每时每刻。 Why?
为什么?
I am on PostgreSQL 10.4. 我在PostgreSQL 10.4上。
you have: 你有:
t=# select '2018-05-31'::timestamp - '2018-02-24'::timestamp;
?column?
----------
96 days
(1 row)
so: 所以:
t=# SELECT DATE_PART('day', '2018-05-31'::timestamp - '2018-02-24');
date_part
-----------
96
(1 row)
try: 尝试:
t=# SELECT DATE_PART('month', justify_interval('2018-05-31'::timestamp - '2018-02-24'::timestamp));
date_part
-----------
3
(1 row)
I think the need of justifying interval prior to using it with date_part
should be noted at 我认为应该在与
date_part
一起使用之前证明间隔的合理性
https://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT , to be clear - true... https://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT-清楚-是的...
Vao Tsun has explained why. Vao Tsun解释了原因。
One good solution for you might be to use the age
function, which formats the interval in years, months and days: 一种适合您的解决方案可能是使用
age
函数,该函数以年,月和日为单位设置时间间隔的格式:
SELECT date_part('month', age('2018-05-31'::timestamp, '2018-02-24'::timestamp));
date_part
-----------
3
(1 row)
That will return more accurate results, because it does not have to assume that every month has 30 days. 这将返回更准确的结果,因为不必假定每个月都有30天。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.