There are several different functions that can be called in Postgres to get the current date and time.
SELECT CURRENT_TIMESTAMP as CURRENT_TIMESTAMP,
TRANSACTION_TIMESTAMP() as TRANSACTION_TIMESTAMP,
LOCALTIMESTAMP as LOCALTIMESTAMP,
NOW() as now,
CLOCK_TIMESTAMP() as CLOCK_TIMESTAMP;
current_timestamp = 2023-02-01 14:04:17.388 -0500
transaction_timestamp = 2023-02-01 14:04:17.388 -0500
localtimestamp = 2023-02-01 14:04:17.388
now = 2023-02-01 14:04:17.388 -0500
clock_timestamp = 2023-02-01 14:04:17.388 -0500
Calling all of these functions return the same information, except that LOCALTIMESTAMP returns the datetime without the time zone offset (I’m in the Eastern United States, currently 5 hours behind UTC).
CURRENT_TIMESTAMP is a SQL standard function, where TRANSACTION_TIMESTAMP and NOW are Postgres functions. NOW is certainly easier to remember, where the TRANSACTION_TIMESTAMP may be a little clearer that it is the same value to be used for multiple calls in a transaction.
All of the functions will return the same value, no matter how many times they are called within a transaction, except for CLOCK_TIMESTAMP. It will return the datetime at the time the function is called. It’s a little clearer when we call the functions twice, with a delay in between.
DO $$ DECLARE v_dummy text; BEGIN RAISE NOTICE '1st Calls'; RAISE NOTICE 'CURRENT_TIMESTAMP = %', CURRENT_TIMESTAMP; RAISE NOTICE 'CLOCK_TIMESTAMP = %', CLOCK_TIMESTAMP(); -- Delay for one second SELECT INTO v_dummy pg_sleep(1); RAISE NOTICE ''; RAISE NOTICE '2nd Calls'; RAISE NOTICE 'CURRENT_TIMESTAMP = %', CURRENT_TIMESTAMP; RAISE NOTICE 'CLOCK_TIMESTAMP = %', CLOCK_TIMESTAMP(); END $$;
Results:
1st Calls
CURRENT_TIMESTAMP = 2023-02-01 14:15:28.878426-05
CLOCK_TIMESTAMP = 2023-02-01 14:15:28.92468-05
2nd Calls
CURRENT_TIMESTAMP = 2023-02-01 14:15:28.878426-05
CLOCK_TIMESTAMP = 2023-02-01 14:15:29.955542-05
There are also CURRENT_DATE and CURRENT_TIME functions to return the date and the time portion of CURRENT_TIMESTAMP.
Links:
Postgres – Datetime Functions
Database Guide – transaction_timestamp