Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date to unix timestamp in postgresql

I have a table with a column abc carrying the unix timestamp (eg. 13898161481435) and I want to run a between dates select.

It would be not efficient to do a

where TO_CHAR(TO_TIMESTAMP(abc / 1000), 'DD/MM/YYYY') > '14/01/2014 00:00:00' and ..;

which would convert every record.

Rather do something like
where abc > ('14/01/2014 00:00:00' tobigint()) and abc < ...

But I cant find any reference, though for the reverse case.

like image 826
javadude Avatar asked Feb 01 '14 05:02

javadude


People also ask

How to get Unix timestamp in PostgreSQL?

In PostgreSQL, we can use the extract() function along with the epoch argument to return the Unix timestamp. We can return the Unix timestamp based on the current date/time, or we can get it based on another specified date/time.

How to convert Unix timestamp to date in PostgreSQL?

In PostgreSQL, we can use the to_timestamp() function to convert a Unix timestamp value to a date/time value. The Unix timestamp (also known as Unix Epoch time, Unix time, or POSIX time) is the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC).

What is epoch time in PostgreSQL?

Posted on 7th November 2022. YES, you can convert EPOCH to Timestamp by merely switching to the present Timestamp in PostgreSQL DBMS. EPOCH time is nothing but the number of seconds from 00:00:00 UTC on 1 January 1970. Till date, without adding the extra leap year days, this is considered.

How do I convert text to date in PostgreSQL?

The TO_DATE function in PostgreSQL is used to converting strings into dates. Its syntax is TO_DATE(text, text) and the return type is date. The TO_TIMESTAMP function converts string data into timestamps with timezone. Its syntax is to_timestamp(text, text) .


2 Answers

Try this

WHERE abc > extract(epoch from timestamp '2014-01-28 00:00:00')

PostgreSQL Docs

like image 194
Vignesh Kumar A Avatar answered Oct 03 '22 21:10

Vignesh Kumar A


You do not need to convert it to char to compare it.

WHERE to_timestamp(abc/1000) > timestamp '2014-01-28 00:00:00'

I don't think that conversion would be very inefficient because timestamps are stored internally in a similar format to epoch secs (admittedly with a different origin and resolution).

If you really want to go the other way:

WHERE abc > extract(epoch from timestamp '2014-01-28 00:00:00')
like image 37
harmic Avatar answered Oct 03 '22 20:10

harmic