How LocalTime() Works in PostgreSQL

In PostgreSQL, the localtime function returns the local time of the day, without the time zone offset.

If you need the time zone offset, use current_time() instead.

Syntax

You can use it in either of the following ways:

localtime
localtime(x)

Where x is an optional precision parameter, which causes the result to be rounded to x number of fractional digits in the seconds field.

Without a precision parameter (the first syntax), the result is given to the full available precision.

Example – Full Precision

Here’s a basic example to demonstrate a result using the full available precision.

SELECT localtime;

Result:

15:50:25.314626

Example – Specific Precision

Here’s an example to demonstrate how to specify the precision.

SELECT localtime(0);

Result:

15:50:44

In this example, I specified a precision of zero, which means that no fractional seconds were returned.

Here’s another example where I specify a number of fractional seconds.

SELECT localtime(3);

Result:

15:50:59.039

Transactions

The actual time is based on the start time of the current transaction. Therefore, it doesn’t change as the transaction progresses.

This allows a single transaction to have a consistent notion of the “current” time, so that multiple modifications within the same transaction bear the same time stamp.

Here’s an example that demonstrates this.

BEGIN;
SELECT localtime;
SELECT pg_sleep(5);
SELECT localtime;
SELECT pg_sleep(5);
SELECT localtime;
COMMIT;

Here’s the full output of my terminal when executing that transaction in psql:

postgres=# BEGIN;
BEGIN
postgres=# SELECT localtime;
    localtime    
-----------------
 09:22:40.096909
(1 row)


postgres=# SELECT pg_sleep(5);
 pg_sleep 
----------
 
(1 row)


postgres=# SELECT localtime;
    localtime    
-----------------
 09:22:40.096909
(1 row)


postgres=# SELECT pg_sleep(5);
 pg_sleep 
----------
 
(1 row)


postgres=# SELECT localtime;
    localtime    
-----------------
 09:22:40.096909
(1 row)


postgres=# COMMIT;
COMMIT

All three time values are identical, even though the pg_sleep() function was used to delay execution between each statement within the transaction.

This is in contrast to statement_timestamp() which does change with each statement.

Multiple Calls within a Statement

It also doesn’t change as the statement progresses.

\x
SELECT 
  localtime,
  pg_sleep(5),
  localtime,
  pg_sleep(5),
  localtime;

Result (using vertical output):

localtime | 09:23:45.108559
pg_sleep  | 
localtime | 09:23:45.108559
pg_sleep  | 
localtime | 09:23:45.108559

All three time values are identical, even though the pg_sleep() function was used to delay execution between each call to localtime.

This is in contrast to the clock_timestamp() function, which does change as it progresses through the statement.

By the way, I used vertical output (also known as expanded output) to make the results slightly more compact.

You can toggle expanded output in psql using \x.