postgres now минус день

9.9. Date/Time Functions and Operators

Table 9-28 shows the available functions for date/time value processing, with details appearing in the following subsections. Table 9-27 illustrates the behaviors of the basic arithmetic operators ( +, *, etc.). For formatting functions, refer to Section 9.8. You should be familiar with the background information on date/time data types from Section 8.5.

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 9-27. Date/Time Operators

Table 9-28. Date/Time Functions

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. Across daylight saving time changes (with the session time zone 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 CST7CDT, timestamp with time zone ‘2005-04-02 12:00-07’ + interval ‘1 day’ will produce timestamp with time zone ‘2005-04-03 12:00-06’, while adding interval ’24 hours’ to the same initial timestamp with time zone produces timestamp with time zone ‘2005-04-03 13:00-06’, as there is a change in daylight saving time at 2005-04-03 02:00 in time zone CST7CDT.

Note there can be ambiguity in the months returned by age because different months have a different number of days. PostgreSQL ‘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 30.

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 double precision. The following are valid field names:

PostgreSQL releases before 8.0 did not follow the conventional numbering of centuries, but just returned the year field divided by 100.

The year field divided by 10

The day of the week as Sunday ( 0) to Saturday ( 6)

Note that extract ‘s day of the week numbering differs from that of the to_char(. ‘D’) function.

For date and timestamp values, the number of seconds since 1970-01-01 00:00:00 UTC (can be negative); for interval values, the total number of seconds in the interval

Here is how you can convert an epoch value back to a time stamp:

(The to_timestamp function encapsulates the above conversion.)

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.

This field is not available in PostgreSQL releases prior to 8.3.

The seconds field, including fractional parts, multiplied by 1 000 000; note that this includes full seconds

Years in the 1900s are in the second millennium. The third millennium started January 1, 2001.

PostgreSQL releases before 8.0 did not follow the conventional numbering of millennia, but just returned the year field divided by 1000.

The seconds field, including fractional parts, multiplied by 1000. Note that this includes full seconds.

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, PostgreSQL uses UT1 because leap seconds are not handled.)

The hour component of the time zone offset

The minute component of the time zone offset

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, and 2006-01-01 is part of the 52nd week of year 2005, while 2012-12-31 is part of the first week of 2013. It’s recommended to use the isoyear field together with week to get consistent results.

The year field. Keep in mind there is no 0 AD, so subtracting BC years from AD years should be done with care.

The extract function is primarily intended for computational processing. For formatting date/time values for display, see Section 9.8.

9.9.2. date_trunc

The function date_trunc is conceptually similar to the trunc function for numbers.

source is a value expression of type timestamp 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 of type timestamp or interval with 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

9.9.3. AT TIME ZONE

The AT TIME ZONE construct allows conversions of time stamps to different time zones. Table 9-29 shows its variants.

Table 9-29. AT TIME ZONE Variants

ExpressionReturn TypeDescription
timestamp without time zone AT TIME ZONE zonetimestamp with time zoneTreat given time stamp without time zone as located in the specified time zone
timestamp with time zone AT TIME ZONE zonetimestamp without time zoneConvert given time stamp with time zone to the new time zone, with no time zone designation
time with time zone AT TIME ZONE zonetime with time zoneConvert given time with time zone to the new time zone

In these expressions, the desired time zone zone can be specified either as a text string (e.g., ‘PST’) 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 8.5.3.

Examples (assuming the local time zone is PST8PDT):

The first example takes a time stamp without time zone and interprets it as MST time (UTC-7), which is then converted to PST (UTC-8) for display. The second example takes a time stamp specified in EST (UTC-5) and converts it to local time in MST (UTC-7).

The function timezone ( zone, timestamp) is equivalent to the SQL-conforming construct timestamp AT TIME ZONE zone.

9.9.4. Current Date/Time

PostgreSQL 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.

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.

Note: Other database systems might advance these values more frequently.

PostgreSQL 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:

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:

Tip: You do not want to use the third form when specifying a DEFAULT clause while creating a table. 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.

9.9.5. Delaying Execution

The following function is available to delay execution of the server process:

pg_sleep makes the current session’s process sleep until seconds seconds have elapsed. seconds is a value of type double precision, so fractional-second delays can be specified. For example:

Note: 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.

Notes

60 if leap seconds are implemented by the operating system

Источник

Postgres now минус день

Все описанные ниже функции и операторы принимают две разновидности типов time или timestamp : с часовым поясом ( time with time zone и timestamp with time zone ) и без него ( time without time zone и timestamp without time zone ). Для краткости здесь они рассматриваются вместе. Кроме того, операторы + и * обладают переместительным свойством (например, date + integer = integer + date); здесь будет приведён только один вариант для каждой пары.

Таблица 9.27. Операторы даты/времени

Таблица 9.28. Функции даты/времени

В дополнение к этим функциям поддерживается SQL-оператор OVERLAPS :

Год, делённый на 10 dow

День недели, считая с воскресенья ( 0 ) до субботы ( 6 )

Для значений timestamp with time zone это число секунд с 1970-01-01 00:00:00 UTC (может быть отрицательным); для значений date и timestamp это число секунд с 1970-01-01 00:00:00 по местному времени, а для interval — общая длительность интервала в секундах

Преобразовать время эпохи назад, в значение дата/время можно так:

День недели, считая с понедельника ( 1 ) до воскресенья ( 7 )

Результат отличается от dow только для воскресенья. Такая нумерация соответствует ISO 8601. isoyear

Этого поля не было в PostgreSQL до версии 8.3. microseconds

Значение секунд с дробной частью, умноженное на 1 000 000; заметьте, что оно включает и целые секунды millennium

Годы 20 века относятся ко второму тысячелетию. Третье тысячелетие началось 1 января 2001 г. milliseconds

Значение секунд с дробной частью, умноженное на 1 000; заметьте, что оно включает и целые секунды. minute

Поле часов в смещении часового пояса timezone_minute

Поле минут в смещении часового пояса week

Поле года. Учтите, что года 0 не было, и это следует иметь в виду, вычитая из годов нашей эры годы до нашей эры.

Функция extract в основном предназначена для вычислительных целей. Функции форматирования даты/времени описаны в Разделе 9.8.

9.9.2. date_trunc

Функция date_trunc работает подобно trunc для чисел.

Параметр поле может принимать следующие значения:

microseconds
milliseconds
second
minute
hour
day
week
month
quarter
year
decade
century
millennium

9.9.3. AT TIME ZONE

Указание AT TIME ZONE позволяет переводить дату/время без часового пояса в дату/время с часовым поясом и обратно, а также пересчитывать значения времени для различных часовых поясов. Все разновидности этого указания проиллюстрированы в Таблице 9.29.

Таблица 9.29. Разновидности AT TIME ZONE

ВыражениеТип результатаОписание
timestamp without time zone AT TIME ZONE часовой_поясtimestamp with time zoneВоспринимает заданное время без указания часового пояса как время в указанном часовом поясе
timestamp with time zone AT TIME ZONE часовой_поясtimestamp without time zoneПереводит данное значение timestamp с часовым поясом в другой часовой пояс, но не сохраняет информацию о нём в результате
time with time zone AT TIME ZONE часовой_поясtime with time zoneПереводит данное время с часовым поясом в другой часовой пояс

В этих выражениях желаемый часовой_пояс можно задать либо в виде текстовой строки (например, ‘America/Los_Angeles’ ), либо как интервал (например, INTERVAL ‘-08:00’ ). В первом случае название часового пояса можно указать любым из способов, описанных в Подразделе 8.5.3.

Примеры (в предположении, что местный часовой пояс America/Los_Angeles ):

В первом примере для значения, заданного без часового пояса, указывается часовой пояс и полученное время выводится в текущем часовом поясе (заданном параметром TimeZone ). Во втором примере значение времени смещается в заданный часовой пояс и выдаётся без указания часового пояса. Этот вариант позволяет хранить и выводить значения с часовым поясом, отличным от текущего. В третьем примере время в часовом поясе Токио пересчитывается для часового пояса Чикаго. При переводе значений времени без даты в другие часовые пояса используются определения часовых поясов, действующие в данный момент.

9.9.4. Текущая дата/время

Postgres Pro предоставляет набор функций, результат которых зависит от текущей даты и времени. Все следующие функции соответствуют стандарту SQL и возвращают значения, отражающие время начала текущей транзакции:

CURRENT_TIME и CURRENT_TIMESTAMP возвращают время с часовым поясом. В результатах LOCALTIME и LOCALTIMESTAMP нет информации о часовом поясе.

Так как эти функции возвращают время начала текущей транзакции, во время транзакции эти значения не меняются. Это считается не ошибкой, а особенностью реализации: цель такого поведения в том, чтобы в одной транзакции « текущее » время было одинаковым и для разных изменений в одной транзакций записывалась одна отметка времени.

Примечание

В других СУБД эти значения могут изменяться чаще.

В Postgres Pro есть также функции, возвращающие время начала текущего оператора, а также текущее время в момент вызова функции. Таким образом, в Postgres Pro есть следующие функции, не описанные в стандарте SQL:

Подсказка

Третья форма не подходит для указания в качестве значения DEFAULT при создании таблицы. Система преобразует now в значение timestamp в момент разбора константы, поэтому, когда будет вставляться значение по умолчанию, в соответствующем столбце окажется время создания таблицы! Первые две формы не будут вычисляться, пока не потребуется значение по умолчанию, так как это вызовы функции. Поэтому они дадут желаемый результат при добавлении строки в таблицу.

9.9.5. Задержка выполнения

В случае необходимости вы можете приостановить выполнение серверного процесса, используя следующие функции:

Примечание

Действительное разрешение интервала задержки зависит от платформы; обычно это 0.01. Фактическая длительность задержки не будет меньше указанного времени, но может быть больше, в зависимости, например от нагрузки на сервер. В частности, не гарантируется, что pg_sleep_until проснётся именно в указанное время, но она точно не проснётся раньше.

Предупреждение

Прежде чем вызывать pg_sleep или её вариации, убедитесь в том, что в текущем сеансе нет ненужных блокировок. В противном случае в состояние ожидания могут перейти и другие сеансы, так что это отразится на системе в целом.

[7] 60, если операционная система поддерживает секунды координации

Источник

9.9. Date/Time Functions and Operators

Table 9-26 shows the available functions for date/time value processing, with details appearing in the following subsections. Table 9-25 illustrates the behaviors of the basic arithmetic operators ( +, *, etc.). For formatting functions, refer to Section 9.8. You should be familiar with the background information on date/time data types from Section 8.5.

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 9-25. Date/Time Operators

Table 9-26. Date/Time Functions

FunctionReturn TypeDescriptionExampleResult
age ( timestamp, timestamp)intervalSubtract arguments, producing a «symbolic» result that uses years and monthsage(timestamp ‘2001-04-10’, timestamp ‘1957-06-13’)43 years 9 mons 27 days
age ( timestamp)intervalSubtract from current_dateage(timestamp ‘1957-06-13’)43 years 8 mons 3 days
current_datedateToday’s date; see Section 9.9.4
current_timetime with time zoneTime of day; see Section 9.9.4
current_timestamptimestamp with time zoneDate and time; see Section 9.9.4
date_part ( text, timestamp)double precisionGet subfield (equivalent to extract ); see Section 9.9.1date_part(‘hour’, timestamp ‘2001-02-16 20:38:40’)20
date_part ( text, interval)double precisionGet subfield (equivalent to extract ); see Section 9.9.1date_part(‘month’, interval ‘2 years 3 months’)3
date_trunc ( text, timestamp)timestampTruncate to specified precision; see also Section 9.9.2date_trunc(‘hour’, timestamp ‘2001-02-16 20:38:40’)2001-02-16 20:00:00
extract ( field from timestamp)double precisionGet subfield; see Section 9.9.1extract(hour from timestamp ‘2001-02-16 20:38:40’)20
extract ( field from interval)double precisionGet subfield; see Section 9.9.1extract(month from interval ‘2 years 3 months’)3
isfinite ( timestamp)booleanTest for finite time stamp (not equal to infinity)isfinite(timestamp ‘2001-02-16 21:28:30’)true
isfinite ( interval)booleanTest for finite intervalisfinite(interval ‘4 hours’)true
justify_hours ( interval)intervalAdjust interval so 24-hour time periods are represented as daysjustify_hours(interval ’24 hours’)1 day
justify_days ( interval)intervalAdjust interval so 30-day time periods are represented as monthsjustify_days(interval ’30 days’)1 month
localtimetimeTime of day; see Section 9.9.4
localtimestamptimestampDate and time; see Section 9.9.4
now ()timestamp with time zoneCurrent date and time (equivalent to current_timestamp ); see Section 9.9.4
timeofday ()textCurrent date and time; see Section 9.9.4

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 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. Across daylight saving time changes (with the session time zone 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 CST7CDT, timestamp with time zone ‘2005-04-02 12:00-07’ + interval ‘1 day’ will produce timestamp with time zone ‘2005-04-03 12:00-06’, while adding interval ’24 hours’ to the same initial timestamp with time zone produces timestamp with time zone ‘2005-04-03 13:00-06’, as there is a change in daylight saving time at 2005-04-03 02:00 in time zone CST7CDT.

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 will be 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 double precision. The following are valid field names:

PostgreSQL releases before 8.0 did not follow the conventional numbering of centuries, but just returned the year field divided by 100.

The year field divided by 10

Note that extract ‘s day of the week numbering is different from that of the to_char function.

For date and timestamp values, the number of seconds since 1970-01-01 00:00:00-00 (can be negative); for interval values, the total number of seconds in the interval

Here is how you can convert an epoch value back to a time stamp:

The seconds field, including fractional parts, multiplied by 1 000 000. Note that this includes full seconds.

Years in the 1900s are in the second millennium. The third millennium starts January 1, 2001.

PostgreSQL releases before 8.0 did not follow the conventional numbering of millennia, but just returned the year field divided by 1000.

The seconds field, including fractional parts, multiplied by 1000. Note that this includes full seconds.

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.

The hour component of the time zone offset

The minute component of the time zone offset

Because of this, it is possible for early January dates to be part of the 52nd or 53rd week of the previous year. For example, 2005-01-01 is part of the 53rd week of year 2004, and 2006-01-01 is part of the 52nd week of year 2005.

The year field. Keep in mind there is no 0 AD, so subtracting BC years from AD years should be done with care.

The extract function is primarily intended for computational processing. For formatting date/time values for display, see Section 9.8.

9.9.2. date_trunc

The function date_trunc is conceptually similar to the trunc function for numbers.

source is a value expression of type timestamp 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 of type timestamp or interval with 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

9.9.3. AT TIME ZONE

The AT TIME ZONE construct allows conversions of time stamps to different time zones. Table 9-27 shows its variants.

Table 9-27. AT TIME ZONE Variants

ExpressionReturn TypeDescription
timestamp without time zone AT TIME ZONE zonetimestamp with time zoneTreat given time stamp without time zone as located in the specified time zone
timestamp with time zone AT TIME ZONE zonetimestamp without time zoneConvert given time stamp with time zone to the new time zone
time with time zone AT TIME ZONE zonetime with time zoneConvert given time with time zone to the new time zone

In these expressions, the desired time zone zone can be specified either as a text string (e.g., ‘PST’) or as an interval (e.g., INTERVAL ‘-08:00’). In the text case, the available zone names are those shown in either Table B-6 or Table B-4.

Examples (supposing that the local time zone is PST8PDT):

The first example takes a time stamp without time zone and interprets it as MST time (UTC-7), which is then converted to PST (UTC-8) for display. The second example takes a time stamp specified in EST (UTC-5) and converts it to local time in MST (UTC-7).

The function timezone ( zone, timestamp) is equivalent to the SQL-conforming construct timestamp AT TIME ZONE zone.

9.9.4. Current Date/Time

The following functions are available to obtain the current date and/or time:

CURRENT_TIME and CURRENT_TIMESTAMP deliver values with time zone; LOCALTIME and LOCALTIMESTAMP deliver values without time zone.

Note: Prior to PostgreSQL 7.2, the precision parameters were unimplemented, and the result was always given in integer seconds.

It is important to know that CURRENT_TIMESTAMP and related 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.

Note: Other database systems may advance these values more frequently.

There is also the function timeofday() which returns the wall-clock time and advances during transactions. For historical reasons timeofday() returns a text string rather than a timestamp value:

All the date/time data types also accept the special literal value now to specify the current date and time. Thus, the following three all return the same result:

Tip: You do not want to use the third form when specifying a DEFAULT clause while creating a table. 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.

Notes

60 if leap seconds are implemented by the operating system

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *