0

I am trying to convert the bigint value to date in PostgreSQL

I am using the below code

SELECT TO_CHAR(TO_TIMESTAMP(1564983632051/ 1000), 
              'YYYY-MM-DD HH24:MI:SS')

then its returning 2019-08-05 07:40:32, which is correct.

However i want to add few hours to it to get local time. Tried with the following query but its throwing an error :

SELECT TO_CHAR(TO_CHAR(TO_TIMESTAMP(1564983632051/ 1000), 
                       'YYYY-MM-DD HH24:MI:SS') + INTERVAL '4 hour')

I do not want to use a separate query, if that's the case i can use select (to_timestamp('2019-08-05 07:40:32', 'YYYY-MM-DD HH24:MI:SS.US') + interval '4 hour')::timestamp; this will return the desired output.

I need both conversion and hours addition in a single query.

1
  • This would be so much easier if you had stored your timestamp in a timestamp column. Commented Aug 16, 2020 at 22:06

2 Answers 2

3

You should add to TIMESTAMP portion, not to portion casted to CHAR :

SELECT TO_CHAR(
               TO_TIMESTAMP(1564983632051/ 1000)+ INTERVAL '4 hour', 
               'YYYY-MM-DD HH24:MI:SS'
               )
Sign up to request clarification or add additional context in comments.

Comments

2

The problem is here:

select pg_typeof(TO_CHAR(TO_TIMESTAMP(1564983632051/ 1000), 'YYYY-MM-DD HH24:MI:SS'));

pg_typeof 
-----------
 text

Adding an interval to a text value is not going to work.

So something like:

select TO_CHAR(TO_TIMESTAMP(1564983632051/1000) + interval '4 hour', 'YYYY-MM-DD HH24:MI:SS') ;
 to_char       
---------------------
 2019-08-05 02:40:32

It is best to stay in a type for operations until the very end. Then apply formatting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.