Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

Please help me.

like image 318
user2515189 Avatar asked Jun 28 '13 10:06

user2515189


People also ask

How do I get the current date and time in PostgreSQL?

To get the current date and time without time zone, you use the LOCALTIME and LOCALTIMESTAMP functions. Notice that NOW() and its related functions return the start time of the current transaction. In other words, the return values of the function calls are the same within a transaction.

How do I extract a date from a timestamp column?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column. (In our example, we use a column of the timestamp data type.)


1 Answers

To get the date from a timestamp (or timestamptz) a simple cast is fastest:

SELECT now()::date

You get the date according to your local time zone either way.

If you want text in a certain format, go with to_char() like @davek provided.

If you want to truncate (round down) the value of a timestamp to a unit of time, use date_trunc():

SELECT date_trunc('minute', now());
like image 135
Erwin Brandstetter Avatar answered Sep 18 '22 20:09

Erwin Brandstetter