PostgreSQL

Convert Epoch to a Timestamp in Postgres

Epoch time, also known as Unix Epoch, refers to Epoch which is commonly used to represent the dates and times in computing. Converting the Epoch to a timestamp involves adding the number of seconds since the Epoch to the base timestamp.

This tutorial covers the basic methods and techniques to convert an Epoch time to a Unix timestamp.

Convert Epoch to Timestamp in PostgreSQL

The most common method of converting an epoch time to a timestamp equivalent is using PostgreSQL’s to_timestamp() function.

The function takes two arguments: the number of seconds since the Epoch and an optional target timezone.

The syntax is as demonstrated in the following:

TO_TIMESTAMP(epoch [, timezone])

Let us take a look at a basic example that converts a given epoch time to a timestamp using the PostgreSQL to_timestamp() function.

SELECT TO_TIMESTAMP(1684327798) AS converted_timestamp;

In the previous example, we use the to_timestamp() function to convert the provided elapsed epoch seconds to timestamp. The resulting value is as follows:

  converted_timestamp
------------------------
 2023-05-17 15:49:58+03
(1 row)

To convert the given epoch value to a given timezone, we can specify the target timezone as shown in the following:

SELECT TO_TIMESTAMP(1621244399, 'America/New_York') AS converted_timestamp;

This should return the timestamp equivalent in the specified timezone. However, it is good to keep in mind that PostgreSQL may fail to automatically convert the input epoch time to timestamp using a target timezone without type casting.

In such a case, we can combine the to_char function as shown in the following:

SELECT to_char(to_timestamp(1684327798) at time zone 'America/New_York', 'YYYY-MM-DD HH24:MI:SS') AS converted_timestamp;

Resulting Output:

converted_timestamp
---------------------
 2023-05-17 08:49:58
(1 row)

By default, the TO_TIMESTAMP() function returns the timestamp in the “YYYY-MM-DD HH:MI: SS” format . However, we can customize the timestamp format using the to_char() function.

SELECT TO_CHAR(TO_TIMESTAMP(1684327798), 'YYYY-MM-DD HH24:MI:SS') AS formatted_timestamp;

Output:

formatted_timestamp
---------------------
 2023-05-17 15:49:58
(1 row)

Conclusion

We explored using the to_timestamp() function to convert a given epoch value to a timestamp value. Again, you can refer to the documentation to learn more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list