Example:
SELECT
SESSIONTIMEZONE,
DT,
TRUNC( (DT - date '1970-01-01') * 86400) AS EPOCH_DT
FROM "test_table"
outputs
| SESSIONTIMEZONE | DT | EPOCH_DT |
|---|---|---|
| Europe/Paris | 1970-01-02 00:00:00 | 86400 |
The desired output (tz_offset +01:00) would look like this:
| SESSIONTIMEZONE | DT | EPOCH_DT |
|---|---|---|
| Europe/Paris | 1970-01-02 00:00:00 | 82800 |
How could the following be changed so that the time zone is taken into account when calculating the Unix time?
TRUNC( (DT - date '1970-01-01') * 86400)
You can convert your date to a timestamp at a specific timezone (you appear to be wanting to use
SESSIONTIMEZONE) and then you can convert that to a timestamp in the UTC time zone (usingAT TIME ZONE 'UTC') and back to a date so you can find the difference from the epoch time:Which, for given the setup:
Outputs:
However, it may make more sense to store your value as a
TIMESTAMP WITH TIME ZONEso that the time zone is stored with the data rather than trying to assume it from the time zone of the local session (otherwise you will get different epoch values for the same query and same data depending on where in the world the database thinks people are from).Then you can use:
Which outputs:
fiddle
If you want something that "works" for both
DATE,TIMESTAMPandTIMESTAMP WITH TIME ZONEthen:However, I still do not think it is a good idea to assume the time zone for
DATEandTIMESTAMPdata types based on theSESSIONTIMEZONE.fiddle