从 PostgreSQL 中的时间戳中提取日期 (yyyy/mm/dd) [英] Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

查看:198
本文介绍了从 PostgreSQL 中的时间戳中提取日期 (yyyy/mm/dd)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想从 PostgreSQL 的时间戳中提取日期部分.

I want to extract just the date part from a timestamp in PostgreSQL.

我需要它是 postgresql DATE 类型,以便我可以将它插入到另一个需要 DATE 值的表中.

I need it to be a postgresql DATE type so I can insert it into another table that expects a DATE value.

例如,如果我有 2011/05/26 09:00:00,我想要 2011/05/26

For example, if I have 2011/05/26 09:00:00, I want 2011/05/26

我试过投射,但我只得到 2011:

timestamp:date
cast(timestamp as date)

我尝试了 to_char()to_date():

I tried to_char() with to_date():

SELECT to_date(to_char(timestamp, 'YYYY/MM/DD'), 'YYYY/MM/DD') 
FROM val3 WHERE id=1;

我试着把它变成一个函数:

CREATE OR REPLACE FUNCTION testing() RETURNS void AS '
DECLARE i_date DATE;
BEGIN
    SELECT to_date(to_char(val1, "YYYY/MM/DD"),"YYYY/MM/DD") 
      INTO i_date FROM exampTable WHERE id=1;
    INSERT INTO foo(testd) VALUES (i);
END

从 PostgreSQL 的时间戳中提取日期 (yyyy/mm/dd) 的最佳方法是什么?

What is the best way to extract date (yyyy/mm/dd) from a timestamp in PostgreSQL?

推荐答案

您可以通过添加 ::date 后缀将时间戳转换为日期.这里,在 psql 中,是一个时间戳:

You can cast your timestamp to a date by suffixing it with ::date. Here, in psql, is a timestamp:

# select '2010-01-01 12:00:00'::timestamp;
      timestamp      
---------------------
 2010-01-01 12:00:00

现在我们将其转换为日期:

Now we'll cast it to a date:

wconrad=# select '2010-01-01 12:00:00'::timestamp::date;
    date    
------------
 2010-01-01

另一方面,您可以使用 date_trunc 函数.它们之间的区别在于后者返回相同的数据类型,如 timestamptz 保持您的时区完整(如果需要).

On the other hand you can use date_trunc function. The difference between them is that the latter returns the same data type like timestamptz keeping your time zone intact (if you need it).

=> select date_trunc('day', now());
       date_trunc
------------------------
 2015-12-15 00:00:00+02
(1 row)

这篇关于从 PostgreSQL 中的时间戳中提取日期 (yyyy/mm/dd)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆