Date/Time Functions and Operators
Date/Time Functions and Operators
Table 8.32 shows the available functions for date/time value processing, with details appearing in the following subsections. Table 8.31 illustrates the behaviors of the basic arithmetic operators (+
, *
, etc.). For formatting functions, refer to Section 8.8. You should be familiar with the background information on date/time data types from Section 7.4.
In addition, the usual comparison operators shown in Table 8.1 are available for the date/time types. Dates and timestamps (with or without time zone) are all comparable, while times (with or without time zone) and intervals can only be compared to other values of the same data type. When comparing a timestamp without time zone to a timestamp with time zone, the former value is assumed to be given in the time zone specified by the "guc-timezone" configuration parameter, and is rotated to UTC for comparison to the latter value (which is already in UTC internally). Similarly, a date value is assumed to represent midnight in the TimeZone
zone when comparing it to a timestamp.
All the functions and operators described below that take time
or timestamp
inputs actually come in two variants: one that takes time with time zone
or timestamp with time zone
, and one that takes time without time zone
or timestamp without time zone
. For brevity, these variants are not shown separately. Also, the +
and *
operators come in commutative pairs (for example both date
+
integer
and integer
+
date
); we show only one of each such pair.
Table Date/Time Operators
Operator Description Example(s) |
---|
Add a number of days to a date
|
Add an interval to a date
|
Add a time-of-day to a date
|
Add intervals
|
Add an interval to a timestamp
|
Add an interval to a time
|
Negate an interval
|
Subtract dates, producing the number of days elapsed
|
Subtract a number of days from a date
|
Subtract an interval from a date
|
Subtract times
|
Subtract an interval from a time
|
Subtract an interval from a timestamp
|
Subtract intervals
|
Subtract timestamps (converting 24-hour intervals into days, similarly to
|
Multiply an interval by a scalar
|
Divide an interval by a scalar
|
Table Date/Time Functions
Function Description Example(s) |
---|
Subtract arguments, producing a “symbolic” result that uses years and months, rather than just days
|
Subtract argument from
|
Current date and time (changes during statement execution); see Section 8.9.5
|
Current date; see Section 8.9.5
|
Current time of day; see Section 8.9.5
|
Current time of day, with limited precision; see Section 8.9.5
|
Current date and time (start of current transaction); see Section 8.9.5
|
Current date and time (start of current transaction), with limited precision; see Section 8.9.5
|
Bin input into specified interval aligned with specified origin; see Section 8.9.3
|
Get timestamp subfield (equivalent to
|
Get interval subfield (equivalent to
|
Truncate to specified precision; see Section 8.9.2
|
Truncate to specified precision in the specified time zone; see Section 8.9.2
|
Truncate to specified precision; see Section 8.9.2
|
Get timestamp subfield; see Section 8.9.1
|
Get interval subfield; see Section 8.9.1
|
Test for finite date (not +/-infinity)
|
Test for finite timestamp (not +/-infinity)
|
Test for finite interval (currently always true)
|
Adjust interval so 30-day time periods are represented as months
|
Adjust interval so 24-hour time periods are represented as days
|
Adjust interval using
|
Current time of day; see Section 8.9.5
|
Current time of day, with limited precision; see Section 8.9.5
|
Current date and time (start of current transaction); see Section 8.9.5
|
Current date and time (start of current transaction), with limited precision; see Section 8.9.5
|
Create date from year, month and day fields (negative years signify BC)
|
Create interval from years, months, weeks, days, hours, minutes and seconds fields, each of which can default to zero
|
Create time from hour, minute and seconds fields
|
Create timestamp from year, month, day, hour, minute and seconds fields (negative years signify BC)
|
Create timestamp with time zone from year, month, day, hour, minute and seconds fields (negative years signify BC). If
|
Current date and time (start of current transaction); see Section 8.9.5
|
Current date and time (start of current statement); see Section 8.9.5
|
Current date and time (like
|
Current date and time (start of current transaction); see Section 8.9.5
|
Convert Unix epoch (seconds since 1970-01-01 00:00:00+00) to timestamp with time zone
|
In addition to these functions, the SQL OVERLAPS
operator is supported:
This expression yields true when two time periods (defined by their endpoints) overlap, false when they do not overlap. The endpoints can be specified as pairs of dates, times, or time stamps; or as a date, time, or time stamp followed by an interval. When a pair of values is provided, either the start or the end can be written first; OVERLAPS
automatically takes the earlier value of the pair as the start. Each time period is considered to represent the half-open interval start
<=
time
<
end
, unless start
and end
are equal in which case it represents that single time instant. This means for instance that two time periods with only an endpoint in common do not overlap.
When adding an interval
value to (or subtracting an interval
value from) a timestamp with time zone
value, the days component advances or decrements the date of the timestamp with time zone
by the indicated number of days, keeping the time of day the same. Across daylight saving time changes (when the session time zone is set to a time zone that recognizes DST), this means interval '1 day'
does not necessarily equal interval '24 hours'
. For example, with the session time zone set to America/Denver
:
This happens because an hour was skipped due to a change in daylight saving time at 2005-04-03 02:00:00
in time zone America/Denver
.
Note there can be ambiguity in the months
field returned by age
because different months have different numbers of days. Tacnode's approach uses the month from the earlier of the two dates when calculating partial months. For example, age('2004-06-01', '2004-04-30')
uses April to yield 1 mon 1 day
, while using May would yield 1 mon 2 days
because May has 31 days, while April has only
Subtraction of dates and timestamps can also be complex. One conceptually simple way to perform subtraction is to convert each value to a number of seconds using EXTRACT(EPOCH FROM ...)
, then subtract the results; this produces the number of seconds between the two values. This will adjust for the number of days in each month, timezone changes, and daylight saving time adjustments. Subtraction of date or timestamp values with the “-
” operator returns the number of days (24-hours) and hours/minutes/seconds between the values, making the same adjustments. The age
function returns years, months, days, and hours/minutes/seconds, performing field-by-field subtraction and then adjusting for negative field values. The following queries illustrate the differences in these approaches. The sample results were produced with timezone = 'US/Eastern'
; there is a daylight saving time change between the two dates used:
EXTRACT
, date_part
The extract
function retrieves subfields such as year or hour from date/time values. source
must be a value expression of type timestamp
, time
, or interval
. (Expressions of type date
are cast to timestamp
and can therefore be used as well.) field
is an identifier or string that selects what field to extract from the source value. The extract
function returns values of type numeric
. The following are valid field names:
century
The century
The first century starts at 0001-01-01 00:00:00 AD, although they did not know it at the time. This definition applies to all Gregorian calendar countries. There is no century number 0, you go from -1 century to 1 century. If you disagree with this, please write your complaint to: Pope, Cathedral Saint-Peter of Roma, Vatican.
day
For
timestamp
values, the day (of the month) field (1–31) ; forinterval
values, the number of daysdecade
The year field divided by 10
dow
The day of the week as Sunday (
0
) to Saturday (6
)Note that
extract
's day of the week numbering differs from that of theto_char(..., 'D')
function.doy
The day of the year (1–365/366)
epoch
For
timestamp with time zone
values, the number of seconds since 1970-01-01 00:00:00 UTC (negative for timestamps before that); fordate
andtimestamp
values, the nominal number of seconds since 1970-01-01 00:00:00, without regard to timezone or daylight-savings rules; forinterval
values, the total number of seconds in the intervalYou can convert an epoch value back to a
timestamp with time zone
withto_timestamp
:Beware that applying
to_timestamp
to an epoch extracted from adate
ortimestamp
value could produce a misleading result: the result will effectively assume that the original value had been given in UTC, which might not be the case.hour
The hour field (0–23)
isodow
The day of the week as Monday (
1
) to Sunday (7
)This is identical to
dow
except for Sunday. This matches the ISO 8601 day of the week numbering.isoyear
The ISO 8601 week-numbering year that the date falls in (not applicable to intervals)
Each ISO 8601 week-numbering year begins with the Monday of the week containing the 4th of January, so in early January or late December the ISO year may be different from the Gregorian year. See the
week
field for more information.This field is not available in PostgreSQL releases prior to
julian
The Julian Date corresponding to the date or timestamp (not applicable to intervals). Timestamps that are not local midnight result in a fractional value. See Section B.7 for more information.
microseconds
The seconds field, including fractional parts, multiplied by 1 000 000; note that this includes full seconds
millennium
The millennium
Years in the 1900s are in the second millennium. The third millennium started January 1,
milliseconds
The seconds field, including fractional parts, multiplied by Note that this includes full seconds.
minute
The minutes field (0–59)
month
For
timestamp
values, the number of the month within the year (1–12) ; forinterval
values, the number of months, modulo 12 (0–11)quarter
The quarter of the year (1–4) that the date is in
second
The seconds field, including any fractional seconds
timezone
The time zone offset from UTC, measured in seconds. Positive values correspond to time zones east of UTC, negative values to zones west of UTC. (Technically, Tacnode does not use UTC because leap seconds are not handled.)
timezone_hour
The hour component of the time zone offset
timezone_minute
The minute component of the time zone offset
week
The number of the ISO 8601 week-numbering week of the year. By definition, ISO weeks start on Mondays and the first week of a year contains January 4 of that year. In other words, the first Thursday of a year is in week 1 of that year.
In the ISO week-numbering system, it is possible for early-January dates to be part of the 52nd or 53rd week of the previous year, and for late-December dates to be part of the first week of the next year. For example,
2005-01-01
is part of the 53rd week of year 2004, and2006-01-01
is part of the 52nd week of year 2005, while2012-12-31
is part of the first week of It's recommended to use theisoyear
field together withweek
to get consistent results.year
The year field. Keep in mind there is no
0 AD
, so subtractingBC
years fromAD
years should be done with care.
When the input value is +/-Infinity, extract
returns +/-Infinity for
monotonically-increasing fields (epoch
, julian
, year
, isoyear
,
decade
, century
, and millennium
). For other fields, NULL is returned.
Tacnode versions before 9.6 returned zero for all cases of infinite input.
The extract
function is primarily intended for computational processing. For formatting
date/time values for display, see Section 8.8.
The date_part
function is modeled on the traditional Ingres equivalent to the SQL-standard function extract
:
Note that here the field
parameter needs to be a string value, not a name. The valid field names for date_part
are the same as for extract
. For historical reasons, the date_part
function returns values of type double precision
. This can result in a loss of precision in certain uses. Using extract
is recommended instead.
date_trunc
The function date_trunc
is conceptually similar to the trunc
function for numbers.
source
is a value expression of type timestamp
, timestamp with time zone
, or interval
. (Values of type date
and time
are cast automatically to timestamp
or interval
, respectively.) field
selects to which precision to truncate the input value. The return value is likewise of type timestamp
, timestamp with time zone
, or interval
, and it has all fields that are less significant than the selected one set to zero (or one, for day and month).
Valid values for field
are:
microseconds |
milliseconds |
second |
minute |
hour |
day |
week |
month |
quarter |
year |
decade |
century |
millennium |
When the input value is of type timestamp with time zone
, the truncation is performed with respect to a particular time zone; for example, truncation to day
produces a value that is midnight in that zone. By default, truncation is done with respect to the current "guc-timezone" setting, but the optional time_zone
argument can be provided to specify a different time zone. The time zone name can be specified in any of the ways described in Section 7.4.3.
A time zone cannot be specified when processing timestamp without time zone
or interval
inputs. These are always taken at face value.
Examples (assuming the local time zone is America/New_York
):
date_bin
The function date_bin
“bins” the input timestamp into the specified interval (the stride) aligned with a specified origin.
source
is a value expression of type timestamp
or timestamp with time zone
. (Values of type date
are cast automatically to timestamp
.) stride
is a value expression of type interval
. The return value is likewise of type timestamp
or timestamp with time zone
, and it marks the beginning of the bin into which the source
is placed.
Examples:
In the case of full units (1 minute, 1 hour, etc.), it gives the same result as the analogous date_trunc
call, but the difference is that date_bin
can truncate to an arbitrary interval.
The stride
interval must be greater than zero and cannot contain units of month or larger.
AT TIME ZONE
The AT TIME ZONE
operator converts time stamp without time zone to/from time stamp with time zone, and time with time zone
values to different time zones. Table 8.33 shows its variants.
Table AT TIME ZONE
Variants
Operator Description Example(s) |
---|
Converts given time stamp without time zone to time stamp with time zone, assuming the given value is in the named time zone.
|
Converts given time stamp with time zone to time stamp without time zone, as the time would appear in that zone.
|
Converts given time with time zone to a new time zone. Since no date is supplied, this uses the currently active UTC offset for the named destination zone.
|
In these expressions, the desired time zone zone
can be specified either as a text value (e.g., 'America/Los_Angeles'
) or as an interval (e.g., INTERVAL '-08:00'
). In the text case, a time zone name can be specified in any of the ways described in Section 7.4.3. The interval case is only useful for zones that have fixed offsets from UTC, so it is not very common in practice.
Examples (assuming the current "guc-timezone" setting is America/Los_Angeles
):
The first example adds a time zone to a value that lacks it, and displays the value using the current TimeZone
setting. The second example shifts the time stamp with time zone value to the specified time zone, and returns the value without a time zone. This allows storage and display of values different from the current TimeZone
setting. The third example converts Tokyo time to Chicago time.
The function `timezone`(`zone`, `timestamp`)
is equivalent to the SQL-conforming construct `timestamp` AT TIME ZONE `zone`
.
Current Date/Time
Tacnode provides a number of functions that return values related to the current date and time. These SQL-standard functions all return values based on the start time of the current transaction:
CURRENT_TIME
and CURRENT_TIMESTAMP
deliver values with time zone; LOCALTIME
and LOCALTIMESTAMP
deliver values without time zone.
CURRENT_TIME
, CURRENT_TIMESTAMP
, LOCALTIME
, and LOCALTIMESTAMP
can optionally take a precision parameter, which causes the result to be rounded to that many fractional digits in the seconds field. Without a precision parameter, the result is given to the full available precision.
Some examples:
Since these functions return the start time of the current transaction, their values do not change during the transaction. This is considered a feature: the intent is to allow 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.
Other database systems might advance these values more frequently.
Tacnode also provides functions that return the start time of the current statement, as well as the actual current time at the instant the function is called. The complete list of non-SQL-standard time functions is:
transaction_timestamp()
is equivalent to CURRENT_TIMESTAMP
, but is named to clearly reflect what it returns. statement_timestamp()
returns the start time of the current statement (more specifically, the time of receipt of the latest command message from the client). statement_timestamp()
and transaction_timestamp()
return the same value during the first command of a transaction, but might differ during subsequent commands. clock_timestamp()
returns the actual current time, and therefore its value changes even within a single SQL command. timeofday()
is a historical Tacnode function. Like clock_timestamp()
, it returns the actual current time, but as a formatted text
string rather than a timestamp with time zone
value. now()
is a traditional Tacnode equivalent to transaction_timestamp()
.
All the date/time data types also accept the special literal value now
to specify the current date and time (again, interpreted as the transaction start time). Thus, the following three all return the same result:
Do not use the third form when specifying a value to be evaluated later, for
example in a DEFAULT
clause for a table column. The system will convert
now
to a timestamp
as soon as the constant is parsed, so that when the
default value is needed, the time of the table creation would be used! The
first two forms will not be evaluated until the default value is used, because
they are function calls. Thus they will give the desired behavior of
defaulting to the time of row insertion. (See also Section
7.4.1.4.)
Delaying Execution
The following functions are available to delay execution of the server process:
pg_sleep
makes the current session's process sleep until the given number of seconds have elapsed. Fractional-second delays can be specified. pg_sleep_for
is a convenience function to allow the sleep time to be specified as an interval
. pg_sleep_until
is a convenience function for when a specific wake-up time is desired. For example:
The effective resolution of the sleep interval is platform-specific; 0.01
seconds is a common value. The sleep delay will be at least as long as
specified. It might be longer depending on factors such as server load. In
particular, pg_sleep_until
is not guaranteed to wake up exactly at the
specified time, but it will not wake up any earlier.
Make sure that your session does not hold more locks than necessary when
calling pg_sleep
or its variants. Otherwise other sessions might have to
wait for your sleeping process, slowing down the entire system.