PostgreSQL NOW() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL NOW()
function to get the current date and time with the time zone.
Introduction to PostgreSQL NOW() function
The NOW()
function returns the current date and time with the time zone of the database server.
Here’s the basic syntax of the NOW()
function:
The NOW()
function doesn’t require any argument. Its return type is the timestamp with time zone. For example:
Output:
Note that the NOW()
function returns the current date and time based on the database server’s time zone setting.
For example, if you change the timezone to ‘Africa/Cairo’ and get the current date and time:
Output:
The output indicates that the value returned by the NOW()
function is adjusted to the new timezone.
Note that to get a complete list of time zones, you can query from the pg_timezone_names
:
Partial output:
If you want to get the current date and time without a timezone, you can cast it explicitly as follows:
Output:
You can use the common date and time operators for the NOW()
function. For example, to get 1 hour from now:
To get this time tomorrow, you add 1 day to the current time:
Output:
To get 2 hours 30 minutes ago, you use the minus (-) operator as follows:
Output:
PostgreSQL NOW() related functions
Besides the NOW()
function, you can use the CURRENT_TIME
or CURRENT_TIMESTAMP
to get the current date and time with the timezone:
Output:
To get the current date and time without a timezone, you use the LOCALTIME
and LOCALTIMESTAMP
functions.
Output:
Notice that NOW()
and its related functions return the start time of the current transaction. In other words, the return values of the function calls are the same within a transaction.
The following example illustrates the concept:
In this example, we called the NOW()
function within a transaction and its return values do not change through the transaction.
Note that the pg_sleep()
function pauses the current session’s process sleep for a specified of seconds.
If you want to get the current date and time that does advance during the transaction, you can use the TIMEOFDAY()
function. Consider the following example:
Output:
After pausing 5 seconds, the current date and time increased.
PostgreSQL NOW() function as default values
You can use the NOW()
function as the default value for a column of a table. For example:
First, create a new table named posts with the created_at
column that has a default value provided by the NOW()
function:
Second, insert a new row into the posts
table:
Third, query data from the posts
table:
Output:
Even though we did not provide the value for the created_at
column, the statement used the value returned by the NOW()
function for that column.
Summary
- Use the PostgreSQL
NOW()
function to get the current date and time with the timezone.