从PostgreSQL中的时间戳提取日期(Yyyy/mm/dd)
我只想从PostgreSQL的时间戳中提取日期部分。
我需要它是postgresql date
键入类型,这样我就可以将其插入另一个表格,该表期望date
值。
例如,如果我有2011/05/26 09:00:00
,我想要2011/05/26
我尝试了铸造,但我只得到2011 :
timestamp:date
cast(timestamp as date)
我尝试了to_char()
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)的最佳方法是什么?
I want to extract just the date part from a timestamp in PostgreSQL.
I need it to be a postgresql DATE
type so I can insert it into another table that expects a DATE
value.
For example, if I have 2011/05/26 09:00:00
, I want 2011/05/26
I tried casting, but I only get 2011:
timestamp:date
cast(timestamp as 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;
I tried to make it a function:
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
What is the best way to extract date (yyyy/mm/dd) from a timestamp in PostgreSQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以通过使用
:: Date
将其施放时间戳到日期。在PSQL中,这里是一个时间戳:现在,我们将其投入到一个日期:
另一方面,您可以使用
date_trunc
函数。它们之间的区别在于,后者返回相同的数据类型,例如timestamptz
保持您的时区完整(如果需要的话)。You can cast your timestamp to a date by suffixing it with
::date
. Here, in psql, is a timestamp:Now we'll cast it to a date:
On the other hand you can use
date_trunc
function. The difference between them is that the latter returns the same data type liketimestamptz
keeping your time zone intact (if you need it).使用 date
> date函数函数函数您可以使用:
测试代码:
测试结果:
Use the date function:
From a character field representation to a date you can use:
Test code:
Test result:
简单地在Postgres中:
In postgres simply :
您是否尝试使用
< myDateTime> :: date
将其施放到日期?Have you tried to cast it to a date, with
<mydatetime>::date
?只需选择
选择日期(Timestamp_column)
,您就可以获得唯一的日期部分。有时
选择Timestamp_column :: Date
可能会返回日期00:00:00
它不会删除00:00:00:00
part。但是我已经看到date(timestamp_column)
在所有情况下都可以正常工作。希望这会有所帮助。Just do
select date(timestamp_column)
and you would get the only the date part.Sometimes doing
select timestamp_column::date
may returndate 00:00:00
where it doesn't remove the00:00:00
part. But I have seendate(timestamp_column)
to work perfectly in all the cases. Hope this helps.这对我来说在Python 2.7中有用
This works for me in python 2.7
另一个测试套件:
Another test kit:
您可以使用
date_trunc('day',field)
。You can use
date_trunc('day', field)
.