5

I have timestamps with time zone (timestamptz) in my table. Can I convert them to numeric or int in unix timestamp format?

I found this question, but it shows only how to convert timestamp without time zone to unix timestamp.

asked Jun 6, 2019 at 17:18
0

3 Answers 3

5

To solve this, I looked here.

For example, I'm in a time zone which is at UTC + 1,

so,

SELECT CURRENT_TIMESTAMP AT TIME ZONE 'UTC';

gives:

2019年06月06日 17:41:00.216647

which is 1 hour behind clock time because I'm on UTC + 1.

So, then from here, I got SELECT EXTRACT(EPOCH FROM ts) FROM data

Combining the two gives:

SELECT EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'));

which for me gives:

date_part
1559843103.53928

YMMV - fiddle available here - put your timestampz into the formula for current_timestamp and you should be golden!

Interstingly, you can check your results here.

p.s. welcome to the forum! :-)

answered Jun 6, 2019 at 17:51
3

The following returns numeric without decimal digits, if that is preferred:

select extract(epoch from current_timestamp)::integer;
answered Dec 26, 2022 at 12:25
3
  • 1
    @JohnK.N. The explicit cast to integer is different? Commented Dec 28, 2022 at 15:58
  • select (EXTRACT(EPOCH FROM created_at) * 1000000)::bigint to get nanoseconds Commented Apr 4, 2023 at 9:15
  • Technically this is give double precision float not numeric, so you may get an approximation weh converting to bigint. Commented Dec 12, 2024 at 9:49
0

0. shell

//test on UTC-8

# UTC-8 locale
$ date -d'2024-12-09T21:05:00' +%s
1733749500
# UTC-0
$ date -d'2024-12-09T21:05:00+00' +%s
1733778300

1. TIMESTAMP .. AT TIME ZONE ..

select extract(epoch from TIMESTAMP '2024-12-09T21:05:00' AT TIME ZONE 'UTC-8')::integer;
 date_part 
------------
 1733749500

2. TIMESTAMPTZ

SELECT EXTRACT(EPOCH FROM TIMESTAMPTZ '2024-12-09 21:05:00+08')::BIGINT AS timestamp_int;
 timestamp_int 
---------------
 1733749500

without tz in time_str, it'll use show timezone;

SELECT EXTRACT(EPOCH FROM TIMESTAMPTZ '2024-12-09 21:05:00')::BIGINT AS timestamp_int;
 timestamp_int 
---------------
 1733749500
answered Dec 11, 2024 at 13:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.