PostgreSQL provides various DateTime functions to work with date and time. One such function is CURRENT_TIME which retrieves the current time with time zone offset. It retrieves the time based on the system on which PostgreSQL is running.
This post presents a thorough guide to getting the current time in Postgres via the CURRENT_TIME function.
Getting Current TIME With Time Zone Using Postgres CURRENT_TIME Function
The CURRENT_TIME function may accept an optional precision argument, as shown in the following syntax:
CURRENT_TIME(precision);
The “precision” parameter determines the decimal places for the seconds' field. Skipping the precision parameter will retrieve the seconds with full available precision. The return type of the stated function is “TIMETZ(TIME WITH TIME ZONE)”.
Example 1: How to Get Current Time in PostgreSQL Via CURRENT_TIME?
To get the current time, all you need to do is execute the CURRENT_TIME function with the help of the Postgres SELECT command:
SELECT CURRENT_TIME;
This way, you can get the current time(with timezone) in Postgres.
Example 2: How to Get Current Time With Specific Precision in PostgreSQL?
In the following code, we will execute the CURRENT_TIME function with and without a precision argument:
SELECT CURRENT_TIME, CURRENT_TIME(3);
The output shows that specifying the precision parameter retrieves the seconds up to the specified precision value.
Example 3: How to Set the Current Time As the Column Default Value?
Let’s create a table named and specify the CURRENT_TIME as the default value for the “arrival_time” column:
CREATE TABLE flight_details( filghtNum INT, departure_time TIME, arrival_time TIME DEFAULT CURRENT_TIME );
The below statement shows how the CURRENT_TIME function works when it is set as the default value of a specific column:
INSERT INTO flight_details (flight_num, departure_time) VALUES (0000, '10:45:00');
A new record has been successfully inserted into the flight_details table. We didn’t specify any value for the “arrival_time” column; however, Postgres will, by default, assign the current time to the “arrival_time” column. The below provided “SELECT *” command illustrates the data of the flight_details table:
SELECT * FROM flight_details;
The output snippet shows that the current time has been assigned to the “arrival_time” column. This way, you can set the current time as the default value of a specific column.
Conclusion
PostgreSQL provides a time function named CURRENT_TIME that retrieves the current time with time zone offset. The CURRENT_TIME function may accept an optional “precision” argument, which determines the decimal places for the seconds' field. Skipping the precision parameter will retrieve the seconds with full available precision. The return type of the stated function is TIMETZ(TIME WITH TIME ZONE). This Postgres blog presented a practical guide on getting the current time in PostgreSQL using the CURRENT_TIME function.