confusion when converting unix timestamp to timestamp with timezone

All we need is an easy explanation of the problem, so here it is.

I have a unix timestamp in seconds and want to convert it to a timestamp with timezone in postgres.

My confusion originates from the fact that the following does not add but removes the time zone:

SELECT to_timestamp(1632610656) at time zone 'Europe/Berlin'

=> "2021-09-26 00:57:36"

If I understand it correctly to_timestamp creates a timestamp with time zone and given this the at time zone 'Europe/Berlin would then remove the time zone? (this feels so strange to me?!).


If I now want to get the timestamp with time zone in Europe/Berlin, is it correct that I need to do the following?

1. Option

SELECT to_timestamp(1632610656) at time zone 'UTC' at time zone 'Europe/Berlin'
=> "2021-09-25 20:57:36+00"

and NOT

2. Option

SELECT to_timestamp(1632610656) at time zone 'Europe/Berlin' at time zone 'Europe/Berlin'
=> "2021-09-25 22:57:36+00"

They obviously have different results. The first one is the correct one, right?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Different from what your intuition would tell you, a timestamp with time zone does not have a certain time zone associated. Rather, it is an “absolute timestamp”.

If you want a timestamp with time zone to be displayed in a certain time zone, you have to set the timezone parameter in your database session:

SET timezone = 'Europe/Berlin';

SELECT to_timestamp(1632610656);

If you want a timestamp without time zone that shows what a Berlin clock would show at that time, use AT TIME ZONE:

SELECT to_timestamp(1632610656) AT TIME ZONE 'Europe/Berlin';

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply