Postgresql – How to always get Timestamp in certain format without having to explicitly define it everytime

postgresqltimestamp

When I run a select on a timestamp I get something like:

2015-01-02T23:22:36.000Z, 1/7/2015 11:03:31 AM

In order to format properly I have to do:

SELECT to_char(entered, 'MM/DD/YYYY HH12:MI:SS AM')
FROM analytics WHERE business_id = 371746;

which is kind of a pain, since I often just do SELECT * and don't specify the fields.

Is there a way to tell Postgres to always return this kind of format 'MM/DD/YYYY HH12:MI:SS AM' from a SELECT without having to specify it every time?

Best Answer

For general preferences you have the DateStyle and LC_TIME settings.

But it would be madness to always truncate fractional seconds automatically - hiding part of the relevant information.

A possible syntax shortcut would be to create a tiny function once:

CREATE OR REPLACE FUNCTION my_ts(timestamp)
  RETURNS text LANGUAGE sql IMMUTABLE AS 
$$SELECT to_char($1, 'MM/DD/YYYY HH12:MI:SS AM')$$;

Then:

SELECT my_ts(entered) FROM analytics WHERE business_id = 371746;