Read more

PostgreSQL: How to change attributes of a timestamp

Arne Hartherz
April 08, 2015Software engineer at makandra GmbH

It's generally not trivial to change a datetime's seconds, minutes, etc in SQL. Here is how it works when speaking PostgreSQL.

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

Consider you have a timestamp column whose seconds you want to zero:

SELECT born_at FROM users;
       born_at
---------------------
 2015-05-01 13:37:42

You can the TO_CHAR function to convert date or time values into a string, and do your changes there:

SELECT TO_CHAR(born_at, 'YYYY-MM-DD HH24:MI:00') FROM users;
       to_char
---------------------
 2015-05-01 13:37:00

Note that this string value can not be used to do other date/time operations, e.g. when you want to UPDATE a datetime column. In such cases, you need to convert your string back into a datetime using TO_TIMESTAMP.

SELECT TO_TIMESTAMP(TO_CHAR(born_at, 'YYYY-MM-DD HH24:MI:00'), 'YYYY-MM-DD HH24:MI:SS') FROM users;
      to_timestamp
------------------------
 2015-05-01 13:37:00+01

Check the PostgreSQL documentation on date type formatting functions Show archive.org snapshot for more information.

Posted by Arne Hartherz to makandra dev (2015-04-08 09:23)