PostgreSQL Tutorial
Data Types
Querying & Filtering Data
Managing Tables
Modifying Data
Conditionals
Control Flow
Transactions & Constraints
Working with JOINS & Schemas
Roles & Permissions
Working with Sets
Subquery & CTEs
User-defined Functions
Important In-Built Functions
PostgreSQL PL/pgSQL
Variables & Constants
Stored Procedures
Working with Triggers
Working with Views & Indexes
Errors & Exception Handling
In PostgreSQL, the CURRENT_TIME
function returns the current time, including the time zone. It's formatted as 'HH:MM:SS' or 'HH:MM:SS.US' (with microseconds) depending on the context, and it includes the time zone information by default.
Here's how you can use CURRENT_TIME
:
1. To get the current time with time zone:
SELECT CURRENT_TIME;
2. Using it in a WHERE clause:
Imagine you have a table log_entries
with a time column entry_time
. If you want to fetch all logs after 3:00 PM today, you might use:
SELECT * FROM log_entries WHERE entry_time > CAST(CURRENT_DATE AS TIMESTAMP) + INTERVAL '15 hour';
(Note: This example assumes entry_time
is a timestamp, so we cast the CURRENT_DATE
to a timestamp and then add the hours to it.)
3. Using it in combination with interval:
To get the time 2 hours 30 minutes ago:
SELECT CURRENT_TIME - INTERVAL '2 hours 30 minutes';
Or to get the time 45 minutes from now:
SELECT CURRENT_TIME + INTERVAL '45 minutes';
Remember, CURRENT_TIME
returns just the time with the time zone. If you only want the time without the time zone, you can use LOCALTIME
. And if you need the current timestamp (including both date and time), you'd use CURRENT_TIMESTAMP
or now()
.
Retrieving the current time with CURRENT_TIME in PostgreSQL:
SELECT CURRENT_TIME;
Using CURRENT_TIME in WHERE clauses in PostgreSQL:
SELECT * FROM your_table WHERE time_column = CURRENT_TIME;
Formatting time with CURRENT_TIME in PostgreSQL:
SELECT TO_CHAR(CURRENT_TIME, 'HH24:MI:SS');
Performing time arithmetic with CURRENT_TIME in PostgreSQL:
SELECT CURRENT_TIME + INTERVAL '1 hour';
Handling time zones with CURRENT_TIME in PostgreSQL:
SET TIME ZONE 'UTC'; SELECT CURRENT_TIME AT TIME ZONE 'America/New_York';
Combining CURRENT_TIME with other time functions in PostgreSQL:
SELECT CURRENT_TIME, EXTRACT(HOUR FROM CURRENT_TIME), AGE(CURRENT_TIME, '12:00:00'::TIME);
Extracting components (hour, minute, second) with CURRENT_TIME in PostgreSQL:
SELECT EXTRACT(HOUR FROM CURRENT_TIME) AS hour, EXTRACT(MINUTE FROM CURRENT_TIME) AS minute, EXTRACT(SECOND FROM CURRENT_TIME) AS second;
Using CURRENT_TIME in INSERT and UPDATE statements in PostgreSQL:
INSERT INTO your_table (column1, time_column) VALUES ('value', CURRENT_TIME); UPDATE your_table SET time_column = CURRENT_TIME WHERE condition;