What is the behavior of PostgreSQL when we cast a DATE
to TIMESTAMP
to TIMESTAMPTZ
What time zone is used?
- PostgreSQL server
- Client that run the query (Current session)
What is the behavior of PostgreSQL when we cast a DATE
to TIMESTAMP
to TIMESTAMPTZ
What time zone is used?
If you cast a date
to a timestamp
, time zones don't play a role, because both data types are without a time zone. The resulting timestamp will be the beginning of the day.
If you cast date
to timestamp with time zone
, resulting timestamp will be the beginning of the date in the time zone defined by the parameter timezone
in your current session.
SHOW timezone;
TimeZone
---------------
Europe/Vienna
(1 row)
SELECT CAST (DATE '2021-01-15' AS timestamp);
timestamp
---------------------
2021-01-15 00:00:00
(1 row)
SELECT CAST (DATE '2021-01-15' AS timestamp with time zone);
timestamptz
------------------------
2021-01-15 00:00:00+01
(1 row)
Casting date to timestamp will append time 00:00:00.0
to the date.
The time zone of the current server session will be used.
By default this is the time zone setting of Postgresql server.
You can change the time zone of the current server session like this:
set time zone 'Europe/Sofia';
I do not think that the time zone of the client has any effect. More on this issue here.
As Adrian Klaver noticed "When dealing with timestamps it's best to assume the worst". Therefore better set the session time zone explicitly.
Given the situation where one needs to change the column type from integer
(as epoc seconds) to timzezonetz
->
casting directly from integer
to timezonetz
is not possible.
but you can do this:
ALTER TABLE table_name ALTER COLUMN column_name TYPE timestamptz
USING column_name::abstime::timestamptz