Skip to content
Advertisement

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

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:

I tried to_char() with to_date():

I tried to make it a function:

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

Advertisement

Answer

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 like timestamptz keeping your time zone intact (if you need it).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement