DEV Community

Cover image for Converting unix epoch time to timestamps in PostgreSQL
Prathamesh Sonpatki
Prathamesh Sonpatki

Posted on

6 1

Converting unix epoch time to timestamps in PostgreSQL

Today we will see how to convert the unix epoch strings to timestamps in PostgreSQL directly.

Let's say we are storing the unix epoch time in database in the timestamp column.

> select timestamp from events;

timestamp   | 
------------+
 1591876140
 1591876200
 1591876260
 1591876320
 1591876380
Enter fullscreen mode Exit fullscreen mode

When querying the database, timestamps in this format are not very useful as we can't figure out which date and time this string is representing.

If we could get a date and time representation, it will be easier to debug the data.

PostgreSQL has to_timestamp function which can be used for this exact purpose.

prathamesh=# select to_timestamp(1591876380);
       to_timestamp
---------------------------
 2020-06-11 17:23:00+05:30
(1 row
Enter fullscreen mode Exit fullscreen mode

As you can see this returns the timestamp in system's timezone. In my case, it returns the timestamp in IST.
If I want the timestamp in some different timezone, I can do that easily using the timezone function.

prathamesh=# select timezone('America/New_york', to_timestamp(1591876380));
      timezone
---------------------
 2020-06-11 07:53:00
(1 row)
Enter fullscreen mode Exit fullscreen mode

The earlier query foe events table can be changes as follows.

> select timezone('America/New_york', to_timestamp(timestamp) from events;
Enter fullscreen mode Exit fullscreen mode

The to_timestamp function also accepts second argument which decides the format of the output. The complete list of formats can be found here.


I had written a post earlier about converting unix epoch strings to Ruby objects earlier. This is useful to convert timestamps to Ruby objects in a Ruby on Rails application.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay