Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a UTC timezone in postgresql to EST (local time)

I am new to PostgreSQL and I was wondering if there is a direct way to just convert the timestamp values in a table to a different timezone using a function. In my case it is UTC to EST.

These are the values for example that I need to convert to EST (not just one value but all the values in the table)

date ------------------- 2015-10-24 16:38:46 2016-01-19 18:27:00 2016-01-24 16:14:34 2016-02-09 23:05:49 2016-02-11 20:46:26 
like image 314
Subu Ganesh Avatar asked Mar 31 '16 18:03

Subu Ganesh


People also ask

How do I convert UTC time to local time in PostgreSQL?

If you have a timestamp without time zone column and you're storing timestamps as UTC, you need to tell PostgreSQL that, and then tell it to convert it to your local time zone.

How do you convert UTC time to local time?

Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.).


2 Answers

Here in London, we are currently 1 hour ahead of UTC. So - if I take your timezone without timestamp and say it is in UTC I will get it printed for my local timezone.

richardh=> SELECT ((timestamp '2015-10-24 16:38:46') AT TIME ZONE 'UTC');         timezone         ------------------------  2015-10-24 17:38:46+01 (1 row) 

But you want "EST" which seems to be somewhere in the Americas, judging by the value returned. You can wrap the expression in a little SQL function if you wanted to.

richardh=> SELECT ((timestamp '2015-10-24 16:38:46') AT TIME ZONE 'UTC') AT TIME ZONE 'EST';       timezone        ---------------------  2015-10-24 11:38:46 (1 row) 

Edit: how to do it in a query

SELECT ((stored_timestamp AT TIME ZONE 'UTC') AT TIME ZONE 'EST') AS local_timestamp FROM my_table; 

You will probably want to get an introductory book on SQL if this sort of thing is causing you problems.

like image 182
Richard Huxton Avatar answered Oct 05 '22 08:10

Richard Huxton


Similarly execute

SELECT '2015-10-24 16:38:46'::timestamp AT time zone 'EST';  timezone ------------------------  2015-10-24 21:38:46+00 (1 row) 
like image 20
Kevin Li Avatar answered Oct 05 '22 10:10

Kevin Li