简体   繁体   English

如何从PostgreSQL选择查询中的时间戳获取日期和时间?

[英]How to get the date and time from timestamp in PostgreSQL select query?

How to get the date and time only up to minutes, not seconds, from timestamp in PostgreSQL. 如何从PostgreSQL中的时间戳获取日期和时间仅最多几分钟,而不是秒。 I need date as well as time. 我需要约会和时间。

For example: 例如:

2000-12-16 12:21:13-05 

From this I need 从此我需要

2000-12-16 12:21 (no seconds and milliseconds only date and time in hours and minutes)

From a timestamp with time zone field, say update_time , how do I get date as well as time like above using PostgreSQL select query. 从带有时区字段的时间戳,比如update_time ,如何使用PostgreSQL选择查询获取上述日期和时间。

Please help me. 请帮我。

To get the date from a timestamp (or timestamptz ) a simple cast is fastest: 要从timestamp (或timestamptz )获取date ,最简单的演员表是最快的:

SELECT now()::date

You get the date according to your local time zone either way. 您可以根据当地时区获得date

If you want text in a certain format, go with to_char() like @davek provided . 如果您想要某种格式的text ,请使用提供的@davek之类的to_char()

If you want to truncate (round down) the value of a timestamp to a unit of time, use date_trunc() : 如果要将timestamp的值截断(向下舍入)为单位时间,请使用date_trunc()

SELECT date_trunc('minute', now());

There are plenty of date-time functions available with postgresql: postgresql有很多日期时间函数:

See the list here 请参阅此处的列表

http://www.postgresql.org/docs/9.1/static/functions-datetime.html http://www.postgresql.org/docs/9.1/static/functions-datetime.html

eg 例如

SELECT EXTRACT(DAY FROM TIMESTAMP '2001-02-16 20:38:40');
Result: 16

For formatting you can use these: 对于格式化,您可以使用这些:

http://www.postgresql.org/docs/9.1/static/functions-formatting.html http://www.postgresql.org/docs/9.1/static/functions-formatting.html

eg 例如

select to_char(current_timestamp, 'YYYY-MM-DD HH24:MI') ...

This should be enough: 这应该足够了:

select now()::date, now()::time
    , pg_typeof(now()), pg_typeof(now()::date), pg_typeof(now()::time)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM