Postgresql как изменить формат даты

9.8. Data Type Formatting Functions The PostgreSQL formatting functions provide a powerful set of tools for converting various data types (date/time, …

The PostgreSQL formatting functions provide a powerful set of tools for converting various data types (date/time, integer, floating point, numeric) to formatted strings and for converting from formatted strings to specific data types. Table 9.26 lists them. These functions all follow a common calling convention: the first argument is the value to be formatted and the second argument is a template that defines the output or input format.

Table 9.26. Formatting Functions

Function

Description

Example(s)

to_char ( timestamp, text ) → text

to_char ( timestamp with time zone, text ) → text

Converts time stamp to string according to the given format.

to_char(timestamp '2002-04-20 17:31:12.66', 'HH12:MI:SS')05:31:12

to_char ( interval, text ) → text

Converts interval to string according to the given format.

to_char(interval '15h 2m 12s', 'HH24:MI:SS')15:02:12

to_char ( numeric_type, text ) → text

Converts number to string according to the given format; available for integer, bigint, numeric, real, double precision.

to_char(125, '999')125

to_char(125.8::real, '999D9')125.8

to_char(-125.8, '999D99S')125.80-

to_date ( text, text ) → date

Converts string to date according to the given format.

to_date('05 Dec 2000', 'DD Mon YYYY')2000-12-05

to_number ( text, text ) → numeric

Converts string to numeric according to the given format.

to_number('12,454.8-', '99G999D9S')-12454.8

to_timestamp ( text, text ) → timestamp with time zone

Converts string to time stamp according to the given format. (See also to_timestamp(double precision) in Table 9.33.)

to_timestamp('05 Dec 2000', 'DD Mon YYYY')2000-12-05 00:00:00-05

Tip

to_timestamp and to_date exist to handle input formats that cannot be converted by simple casting. For most standard date/time formats, simply casting the source string to the required data type works, and is much easier. Similarly, to_number is unnecessary for standard numeric representations.

In a to_char output template string, there are certain patterns that are recognized and replaced with appropriately-formatted data based on the given value. Any text that is not a template pattern is simply copied verbatim. Similarly, in an input template string (for the other functions), template patterns identify the values to be supplied by the input data string. If there are characters in the template string that are not template patterns, the corresponding characters in the input data string are simply skipped over (whether or not they are equal to the template string characters).

Table 9.27 shows the template patterns available for formatting date and time values.

Table 9.27. Template Patterns for Date/Time Formatting

Pattern Description
HH hour of day (01–12)
HH12 hour of day (01–12)
HH24 hour of day (00–23)
MI minute (00–59)
SS second (00–59)
MS millisecond (000–999)
US microsecond (000000–999999)
FF1 tenth of second (0–9)
FF2 hundredth of second (00–99)
FF3 millisecond (000–999)
FF4 tenth of a millisecond (0000–9999)
FF5 hundredth of a millisecond (00000–99999)
FF6 microsecond (000000–999999)
SSSS, SSSSS seconds past midnight (0–86399)
AM, am, PM or pm meridiem indicator (without periods)
A.M., a.m., P.M. or p.m. meridiem indicator (with periods)
Y,YYY year (4 or more digits) with comma
YYYY year (4 or more digits)
YYY last 3 digits of year
YY last 2 digits of year
Y last digit of year
IYYY ISO 8601 week-numbering year (4 or more digits)
IYY last 3 digits of ISO 8601 week-numbering year
IY last 2 digits of ISO 8601 week-numbering year
I last digit of ISO 8601 week-numbering year
BC, bc, AD or ad era indicator (without periods)
B.C., b.c., A.D. or a.d. era indicator (with periods)
MONTH full upper case month name (blank-padded to 9 chars)
Month full capitalized month name (blank-padded to 9 chars)
month full lower case month name (blank-padded to 9 chars)
MON abbreviated upper case month name (3 chars in English, localized lengths vary)
Mon abbreviated capitalized month name (3 chars in English, localized lengths vary)
mon abbreviated lower case month name (3 chars in English, localized lengths vary)
MM month number (01–12)
DAY full upper case day name (blank-padded to 9 chars)
Day full capitalized day name (blank-padded to 9 chars)
day full lower case day name (blank-padded to 9 chars)
DY abbreviated upper case day name (3 chars in English, localized lengths vary)
Dy abbreviated capitalized day name (3 chars in English, localized lengths vary)
dy abbreviated lower case day name (3 chars in English, localized lengths vary)
DDD day of year (001–366)
IDDD day of ISO 8601 week-numbering year (001–371; day 1 of the year is Monday of the first ISO week)
DD day of month (01–31)
D day of the week, Sunday (1) to Saturday (7)
ID ISO 8601 day of the week, Monday (1) to Sunday (7)
W week of month (1–5) (the first week starts on the first day of the month)
WW week number of year (1–53) (the first week starts on the first day of the year)
IW week number of ISO 8601 week-numbering year (01–53; the first Thursday of the year is in week 1)
CC century (2 digits) (the twenty-first century starts on 2001-01-01)
J Julian Date (integer days since November 24, 4714 BC at local midnight; see Section B.7)
Q quarter
RM month in upper case Roman numerals (I–XII; I=January)
rm month in lower case Roman numerals (i–xii; i=January)
TZ upper case time-zone abbreviation (only supported in to_char)
tz lower case time-zone abbreviation (only supported in to_char)
TZH time-zone hours
TZM time-zone minutes
OF time-zone offset from UTC (only supported in to_char)

Modifiers can be applied to any template pattern to alter its behavior. For example, FMMonth is the Month pattern with the FM modifier. Table 9.28 shows the modifier patterns for date/time formatting.

Table 9.28. Template Pattern Modifiers for Date/Time Formatting

Modifier Description Example
FM prefix fill mode (suppress leading zeroes and padding blanks) FMMonth
TH suffix upper case ordinal number suffix DDTH, e.g., 12TH
th suffix lower case ordinal number suffix DDth, e.g., 12th
FX prefix fixed format global option (see usage notes) FX Month DD Day
TM prefix translation mode (use localized day and month names based on lc_time) TMMonth
SP suffix spell mode (not implemented) DDSP

Usage notes for date/time formatting:

  • FM suppresses leading zeroes and trailing blanks that would otherwise be added to make the output of a pattern be fixed-width. In PostgreSQL, FM modifies only the next specification, while in Oracle FM affects all subsequent specifications, and repeated FM modifiers toggle fill mode on and off.

  • TM suppresses trailing blanks whether or not FM is specified.

  • to_timestamp and to_date ignore letter case in the input; so for example MON, Mon, and mon all accept the same strings. When using the TM modifier, case-folding is done according to the rules of the function’s input collation (see Section 24.2).

  • to_timestamp and to_date skip multiple blank spaces at the beginning of the input string and around date and time values unless the FX option is used. For example, to_timestamp(' 2000    JUN', 'YYYY MON') and to_timestamp('2000 - JUN', 'YYYY-MON') work, but to_timestamp('2000    JUN', 'FXYYYY MON') returns an error because to_timestamp expects only a single space. FX must be specified as the first item in the template.

  • A separator (a space or non-letter/non-digit character) in the template string of to_timestamp and to_date matches any single separator in the input string or is skipped, unless the FX option is used. For example, to_timestamp('2000JUN', 'YYYY///MON') and to_timestamp('2000/JUN', 'YYYY MON') work, but to_timestamp('2000//JUN', 'YYYY/MON') returns an error because the number of separators in the input string exceeds the number of separators in the template.

    If FX is specified, a separator in the template string matches exactly one character in the input string. But note that the input string character is not required to be the same as the separator from the template string. For example, to_timestamp('2000/JUN', 'FXYYYY MON') works, but to_timestamp('2000/JUN', 'FXYYYY  MON') returns an error because the second space in the template string consumes the letter J from the input string.

  • A TZH template pattern can match a signed number. Without the FX option, minus signs may be ambiguous, and could be interpreted as a separator. This ambiguity is resolved as follows: If the number of separators before TZH in the template string is less than the number of separators before the minus sign in the input string, the minus sign is interpreted as part of TZH. Otherwise, the minus sign is considered to be a separator between values. For example, to_timestamp('2000 -10', 'YYYY TZH') matches -10 to TZH, but to_timestamp('2000 -10', 'YYYY  TZH') matches 10 to TZH.

  • Ordinary text is allowed in to_char templates and will be output literally. You can put a substring in double quotes to force it to be interpreted as literal text even if it contains template patterns. For example, in '"Hello Year "YYYY', the YYYY will be replaced by the year data, but the single Y in Year will not be. In to_date, to_number, and to_timestamp, literal text and double-quoted strings result in skipping the number of characters contained in the string; for example "XX" skips two input characters (whether or not they are XX).

    Tip

    Prior to PostgreSQL 12, it was possible to skip arbitrary text in the input string using non-letter or non-digit characters. For example, to_timestamp('2000y6m1d', 'yyyy-MM-DD') used to work. Now you can only use letter characters for this purpose. For example, to_timestamp('2000y6m1d', 'yyyytMMtDDt') and to_timestamp('2000y6m1d', 'yyyy"y"MM"m"DD"d"') skip y, m, and d.

  • If you want to have a double quote in the output you must precede it with a backslash, for example '"YYYY Month"'. Backslashes are not otherwise special outside of double-quoted strings. Within a double-quoted string, a backslash causes the next character to be taken literally, whatever it is (but this has no special effect unless the next character is a double quote or another backslash).

  • In to_timestamp and to_date, if the year format specification is less than four digits, e.g., YYY, and the supplied year is less than four digits, the year will be adjusted to be nearest to the year 2020, e.g., 95 becomes 1995.

  • In to_timestamp and to_date, negative years are treated as signifying BC. If you write both a negative year and an explicit BC field, you get AD again. An input of year zero is treated as 1 BC.

  • In to_timestamp and to_date, the YYYY conversion has a restriction when processing years with more than 4 digits. You must use some non-digit character or template after YYYY, otherwise the year is always interpreted as 4 digits. For example (with the year 20000): to_date('200001131', 'YYYYMMDD') will be interpreted as a 4-digit year; instead use a non-digit separator after the year, like to_date('20000-1131', 'YYYY-MMDD') or to_date('20000Nov31', 'YYYYMonDD').

  • In to_timestamp and to_date, the CC (century) field is accepted but ignored if there is a YYY, YYYY or Y,YYY field. If CC is used with YY or Y then the result is computed as that year in the specified century. If the century is specified but the year is not, the first year of the century is assumed.

  • In to_timestamp and to_date, weekday names or numbers (DAY, D, and related field types) are accepted but are ignored for purposes of computing the result. The same is true for quarter (Q) fields.

  • In to_timestamp and to_date, an ISO 8601 week-numbering date (as distinct from a Gregorian date) can be specified in one of two ways:

    • Year, week number, and weekday: for example to_date('2006-42-4', 'IYYY-IW-ID') returns the date 2006-10-19. If you omit the weekday it is assumed to be 1 (Monday).

    • Year and day of year: for example to_date('2006-291', 'IYYY-IDDD') also returns 2006-10-19.

    Attempting to enter a date using a mixture of ISO 8601 week-numbering fields and Gregorian date fields is nonsensical, and will cause an error. In the context of an ISO 8601 week-numbering year, the concept of a month or day of month has no meaning. In the context of a Gregorian year, the ISO week has no meaning.

    Caution

    While to_date will reject a mixture of Gregorian and ISO week-numbering date fields, to_char will not, since output format specifications like YYYY-MM-DD (IYYY-IDDD) can be useful. But avoid writing something like IYYY-MM-DD; that would yield surprising results near the start of the year. (See Section 9.9.1 for more information.)

  • In to_timestamp, millisecond (MS) or microsecond (US) fields are used as the seconds digits after the decimal point. For example to_timestamp('12.3', 'SS.MS') is not 3 milliseconds, but 300, because the conversion treats it as 12 + 0.3 seconds. So, for the format SS.MS, the input values 12.3, 12.30, and 12.300 specify the same number of milliseconds. To get three milliseconds, one must write 12.003, which the conversion treats as 12 + 0.003 = 12.003 seconds.

    Here is a more complex example: to_timestamp('15:12:02.020.001230', 'HH24:MI:SS.MS.US') is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds + 1230 microseconds = 2.021230 seconds.

  • to_char(..., 'ID')‘s day of the week numbering matches the extract(isodow from ...) function, but to_char(..., 'D')‘s does not match extract(dow from ...)‘s day numbering.

  • to_char(interval) formats HH and HH12 as shown on a 12-hour clock, for example zero hours and 36 hours both output as 12, while HH24 outputs the full hour value, which can exceed 23 in an interval value.

Table 9.29 shows the template patterns available for formatting numeric values.

Table 9.29. Template Patterns for Numeric Formatting

Pattern Description
9 digit position (can be dropped if insignificant)
0 digit position (will not be dropped, even if insignificant)
. (period) decimal point
, (comma) group (thousands) separator
PR negative value in angle brackets
S sign anchored to number (uses locale)
L currency symbol (uses locale)
D decimal point (uses locale)
G group separator (uses locale)
MI minus sign in specified position (if number < 0)
PL plus sign in specified position (if number > 0)
SG plus/minus sign in specified position
RN Roman numeral (input between 1 and 3999)
TH or th ordinal number suffix
V shift specified number of digits (see notes)
EEEE exponent for scientific notation

Usage notes for numeric formatting:

  • 0 specifies a digit position that will always be printed, even if it contains a leading/trailing zero. 9 also specifies a digit position, but if it is a leading zero then it will be replaced by a space, while if it is a trailing zero and fill mode is specified then it will be deleted. (For to_number(), these two pattern characters are equivalent.)

  • The pattern characters S, L, D, and G represent the sign, currency symbol, decimal point, and thousands separator characters defined by the current locale (see lc_monetary and lc_numeric). The pattern characters period and comma represent those exact characters, with the meanings of decimal point and thousands separator, regardless of locale.

  • If no explicit provision is made for a sign in to_char()‘s pattern, one column will be reserved for the sign, and it will be anchored to (appear just left of) the number. If S appears just left of some 9‘s, it will likewise be anchored to the number.

  • A sign formatted using SG, PL, or MI is not anchored to the number; for example, to_char(-12, 'MI9999') produces '-  12' but to_char(-12, 'S9999') produces '  -12'. (The Oracle implementation does not allow the use of MI before 9, but rather requires that 9 precede MI.)

  • TH does not convert values less than zero and does not convert fractional numbers.

  • PL, SG, and TH are PostgreSQL extensions.

  • In to_number, if non-data template patterns such as L or TH are used, the corresponding number of input characters are skipped, whether or not they match the template pattern, unless they are data characters (that is, digits, sign, decimal point, or comma). For example, TH would skip two non-data characters.

  • V with to_char multiplies the input values by 10^n, where n is the number of digits following V. V with to_number divides in a similar manner. to_char and to_number do not support the use of V combined with a decimal point (e.g., 99.9V99 is not allowed).

  • EEEE (scientific notation) cannot be used in combination with any of the other formatting patterns or modifiers other than digit and decimal point patterns, and must be at the end of the format string (e.g., 9.99EEEE is a valid pattern).

Certain modifiers can be applied to any template pattern to alter its behavior. For example, FM99.99 is the 99.99 pattern with the FM modifier. Table 9.30 shows the modifier patterns for numeric formatting.

Table 9.30. Template Pattern Modifiers for Numeric Formatting

Modifier Description Example
FM prefix fill mode (suppress trailing zeroes and padding blanks) FM99.99
TH suffix upper case ordinal number suffix 999TH
th suffix lower case ordinal number suffix 999th

Table 9.31 shows some examples of the use of the to_char function.

Table 9.31. to_char Examples

Expression Result
to_char(current_timestamp, 'Day, DD  HH12:MI:SS') 'Tuesday  , 06  05:39:18'
to_char(current_timestamp, 'FMDay, FMDD  HH12:MI:SS') 'Tuesday, 6  05:39:18'
to_char(-0.1, '99.99') '  -.10'
to_char(-0.1, 'FM9.99') '-.1'
to_char(-0.1, 'FM90.99') '-0.1'
to_char(0.1, '0.9') ' 0.1'
to_char(12, '9990999.9') '    0012.0'
to_char(12, 'FM9990999.9') '0012.'
to_char(485, '999') ' 485'
to_char(-485, '999') '-485'
to_char(485, '9 9 9') ' 4 8 5'
to_char(1485, '9,999') ' 1,485'
to_char(1485, '9G999') ' 1 485'
to_char(148.5, '999.999') ' 148.500'
to_char(148.5, 'FM999.999') '148.5'
to_char(148.5, 'FM999.990') '148.500'
to_char(148.5, '999D999') ' 148,500'
to_char(3148.5, '9G999D999') ' 3 148,500'
to_char(-485, '999S') '485-'
to_char(-485, '999MI') '485-'
to_char(485, '999MI') '485 '
to_char(485, 'FM999MI') '485'
to_char(485, 'PL999') '+485'
to_char(485, 'SG999') '+485'
to_char(-485, 'SG999') '-485'
to_char(-485, '9SG99') '4-85'
to_char(-485, '999PR') '<485>'
to_char(485, 'L999') 'DM 485'
to_char(485, 'RN') '        CDLXXXV'
to_char(485, 'FMRN') 'CDLXXXV'
to_char(5.2, 'FMRN') 'V'
to_char(482, '999th') ' 482nd'
to_char(485, '"Good number:"999') 'Good number: 485'
to_char(485.8, '"Pre:"999" Post:" .999') 'Pre: 485 Post: .800'
to_char(12, '99V999') ' 12000'
to_char(12.4, '99V999') ' 12400'
to_char(12.45, '99V9') ' 125'
to_char(0.0004859, '9.99EEEE') ' 4.86e-04'

This documentation is for an unsupported version of PostgreSQL.
You may want to view the same page for the
current
version, or one of the other supported versions listed above instead.

The PostgreSQL formatting functions provide a powerful set of tools for converting various data types (date/time, integer, floating point, numeric) to formatted strings and for converting from formatted strings to specific data types. Table 9.23 lists them. These functions all follow a common calling convention: the first argument is the value to be formatted and the second argument is a template that defines the output or input format.

Table 9.23. Formatting Functions

Function Return Type Description Example
to_char(timestamp, text) text convert time stamp to string to_char(current_timestamp, 'HH12:MI:SS')
to_char(interval, text) text convert interval to string to_char(interval '15h 2m 12s', 'HH24:MI:SS')
to_char(int, text) text convert integer to string to_char(125, '999')
to_char(double precision, text) text convert real/double precision to string to_char(125.8::real, '999D9')
to_char(numeric, text) text convert numeric to string to_char(-125.8, '999D99S')
to_date(text, text) date convert string to date to_date('05 Dec 2000', 'DD Mon YYYY')
to_number(text, text) numeric convert string to numeric to_number('12,454.8-', '99G999D9S')
to_timestamp(text, text) timestamp with time zone convert string to time stamp to_timestamp('05 Dec 2000', 'DD Mon YYYY')

Note

There is also a single-argument to_timestamp function; see Table 9.30.

Tip

to_timestamp and to_date exist to handle input formats that cannot be converted by simple casting. For most standard date/time formats, simply casting the source string to the required data type works, and is much easier. Similarly, to_number is unnecessary for standard numeric representations.

In a to_char output template string, there are certain patterns that are recognized and replaced with appropriately-formatted data based on the given value. Any text that is not a template pattern is simply copied verbatim. Similarly, in an input template string (for the other functions), template patterns identify the values to be supplied by the input data string.

Table 9.24 shows the template patterns available for formatting date and time values.

Table 9.24. Template Patterns for Date/Time Formatting

Pattern Description
HH hour of day (01-12)
HH12 hour of day (01-12)
HH24 hour of day (00-23)
MI minute (00-59)
SS second (00-59)
MS millisecond (000-999)
US microsecond (000000-999999)
SSSS seconds past midnight (0-86399)
AM, am, PM or pm meridiem indicator (without periods)
A.M., a.m., P.M. or p.m. meridiem indicator (with periods)
Y,YYY year (4 or more digits) with comma
YYYY year (4 or more digits)
YYY last 3 digits of year
YY last 2 digits of year
Y last digit of year
IYYY ISO 8601 week-numbering year (4 or more digits)
IYY last 3 digits of ISO 8601 week-numbering year
IY last 2 digits of ISO 8601 week-numbering year
I last digit of ISO 8601 week-numbering year
BC, bc, AD or ad era indicator (without periods)
B.C., b.c., A.D. or a.d. era indicator (with periods)
MONTH full upper case month name (blank-padded to 9 chars)
Month full capitalized month name (blank-padded to 9 chars)
month full lower case month name (blank-padded to 9 chars)
MON abbreviated upper case month name (3 chars in English, localized lengths vary)
Mon abbreviated capitalized month name (3 chars in English, localized lengths vary)
mon abbreviated lower case month name (3 chars in English, localized lengths vary)
MM month number (01-12)
DAY full upper case day name (blank-padded to 9 chars)
Day full capitalized day name (blank-padded to 9 chars)
day full lower case day name (blank-padded to 9 chars)
DY abbreviated upper case day name (3 chars in English, localized lengths vary)
Dy abbreviated capitalized day name (3 chars in English, localized lengths vary)
dy abbreviated lower case day name (3 chars in English, localized lengths vary)
DDD day of year (001-366)
IDDD day of ISO 8601 week-numbering year (001-371; day 1 of the year is Monday of the first ISO week)
DD day of month (01-31)
D day of the week, Sunday (1) to Saturday (7)
ID ISO 8601 day of the week, Monday (1) to Sunday (7)
W week of month (1-5) (the first week starts on the first day of the month)
WW week number of year (1-53) (the first week starts on the first day of the year)
IW week number of ISO 8601 week-numbering year (01-53; the first Thursday of the year is in week 1)
CC century (2 digits) (the twenty-first century starts on 2001-01-01)
J Julian Date (integer days since November 24, 4714 BC at local midnight; see Section B.7)
Q quarter
RM month in upper case Roman numerals (I-XII; I=January)
rm month in lower case Roman numerals (i-xii; i=January)
TZ upper case time-zone abbreviation (only supported in to_char)
tz lower case time-zone abbreviation (only supported in to_char)
OF time-zone offset from UTC (only supported in to_char)

Modifiers can be applied to any template pattern to alter its behavior. For example, FMMonth is the Month pattern with the FM modifier. Table 9.25 shows the modifier patterns for date/time formatting.

Table 9.25. Template Pattern Modifiers for Date/Time Formatting

Modifier Description Example
FM prefix fill mode (suppress leading zeroes and padding blanks) FMMonth
TH suffix upper case ordinal number suffix DDTH, e.g., 12TH
th suffix lower case ordinal number suffix DDth, e.g., 12th
FX prefix fixed format global option (see usage notes) FX Month DD Day
TM prefix translation mode (print localized day and month names based on lc_time) TMMonth
SP suffix spell mode (not implemented) DDSP

Usage notes for date/time formatting:

  • FM suppresses leading zeroes and trailing blanks that would otherwise be added to make the output of a pattern be fixed-width. In PostgreSQL, FM modifies only the next specification, while in Oracle FM affects all subsequent specifications, and repeated FM modifiers toggle fill mode on and off.

  • TM does not include trailing blanks. to_timestamp and to_date ignore the TM modifier.

  • to_timestamp and to_date skip multiple blank spaces in the input string unless the FX option is used. For example, to_timestamp('2000    JUN', 'YYYY MON') works, but to_timestamp('2000    JUN', 'FXYYYY MON') returns an error because to_timestamp expects one space only. FX must be specified as the first item in the template.

  • Ordinary text is allowed in to_char templates and will be output literally. You can put a substring in double quotes to force it to be interpreted as literal text even if it contains pattern key words. For example, in '"Hello Year "YYYY', the YYYY will be replaced by the year data, but the single Y in Year will not be. In to_date, to_number, and to_timestamp, double-quoted strings skip the number of input characters contained in the string, e.g., "XX" skips two input characters.

  • If you want to have a double quote in the output you must precede it with a backslash, for example '"YYYY Month"'.

  • In to_timestamp and to_date, if the year format specification is less than four digits, e.g., YYY, and the supplied year is less than four digits, the year will be adjusted to be nearest to the year 2020, e.g., 95 becomes 1995.

  • In to_timestamp and to_date, negative years are treated as signifying BC. If you write both a negative year and an explicit BC field, you get AD again. An input of year zero is treated as 1 BC.

  • In to_timestamp and to_date, the YYYY conversion has a restriction when processing years with more than 4 digits. You must use some non-digit character or template after YYYY, otherwise the year is always interpreted as 4 digits. For example (with the year 20000): to_date('200001131', 'YYYYMMDD') will be interpreted as a 4-digit year; instead use a non-digit separator after the year, like to_date('20000-1131', 'YYYY-MMDD') or to_date('20000Nov31', 'YYYYMonDD').

  • In to_timestamp and to_date, the CC (century) field is accepted but ignored if there is a YYY, YYYY or Y,YYY field. If CC is used with YY or Y then the result is computed as that year in the specified century. If the century is specified but the year is not, the first year of the century is assumed.

  • In to_timestamp and to_date, weekday names or numbers (DAY, D, and related field types) are accepted but are ignored for purposes of computing the result. The same is true for quarter (Q) fields.

  • In to_timestamp and to_date, an ISO 8601 week-numbering date (as distinct from a Gregorian date) can be specified in one of two ways:

    • Year, week number, and weekday: for example to_date('2006-42-4', 'IYYY-IW-ID') returns the date 2006-10-19. If you omit the weekday it is assumed to be 1 (Monday).

    • Year and day of year: for example to_date('2006-291', 'IYYY-IDDD') also returns 2006-10-19.

    Attempting to enter a date using a mixture of ISO 8601 week-numbering fields and Gregorian date fields is nonsensical, and will cause an error. In the context of an ISO 8601 week-numbering year, the concept of a month or day of month has no meaning. In the context of a Gregorian year, the ISO week has no meaning.

    Caution

    While to_date will reject a mixture of Gregorian and ISO week-numbering date fields, to_char will not, since output format specifications like YYYY-MM-DD (IYYY-IDDD) can be useful. But avoid writing something like IYYY-MM-DD; that would yield surprising results near the start of the year. (See Section 9.9.1 for more information.)

  • In to_timestamp, millisecond (MS) or microsecond (US) fields are used as the seconds digits after the decimal point. For example to_timestamp('12.3', 'SS.MS') is not 3 milliseconds, but 300, because the conversion treats it as 12 + 0.3 seconds. So, for the format SS.MS, the input values 12.3, 12.30, and 12.300 specify the same number of milliseconds. To get three milliseconds, one must write 12.003, which the conversion treats as 12 + 0.003 = 12.003 seconds.

    Here is a more complex example: to_timestamp('15:12:02.020.001230', 'HH24:MI:SS.MS.US') is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds + 1230 microseconds = 2.021230 seconds.

  • to_char(..., 'ID')‘s day of the week numbering matches the extract(isodow from ...) function, but to_char(..., 'D')‘s does not match extract(dow from ...)‘s day numbering.

  • to_char(interval) formats HH and HH12 as shown on a 12-hour clock, for example zero hours and 36 hours both output as 12, while HH24 outputs the full hour value, which can exceed 23 in an interval value.

Table 9.26 shows the template patterns available for formatting numeric values.

Table 9.26. Template Patterns for Numeric Formatting

Pattern Description
9 digit position (can be dropped if insignificant)
0 digit position (will not be dropped, even if insignificant)
. (period) decimal point
, (comma) group (thousands) separator
PR negative value in angle brackets
S sign anchored to number (uses locale)
L currency symbol (uses locale)
D decimal point (uses locale)
G group separator (uses locale)
MI minus sign in specified position (if number < 0)
PL plus sign in specified position (if number > 0)
SG plus/minus sign in specified position
RN Roman numeral (input between 1 and 3999)
TH or th ordinal number suffix
V shift specified number of digits (see notes)
EEEE exponent for scientific notation

Usage notes for numeric formatting:

  • 0 specifies a digit position that will always be printed, even if it contains a leading/trailing zero. 9 also specifies a digit position, but if it is a leading zero then it will be replaced by a space, while if it is a trailing zero and fill mode is specified then it will be deleted. (For to_number(), these two pattern characters are equivalent.)

  • The pattern characters S, L, D, and G represent the sign, currency symbol, decimal point, and thousands separator characters defined by the current locale (see lc_monetary and lc_numeric). The pattern characters period and comma represent those exact characters, with the meanings of decimal point and thousands separator, regardless of locale.

  • If no explicit provision is made for a sign in to_char()‘s pattern, one column will be reserved for the sign, and it will be anchored to (appear just left of) the number. If S appears just left of some 9‘s, it will likewise be anchored to the number.

  • A sign formatted using SG, PL, or MI is not anchored to the number; for example, to_char(-12, 'MI9999') produces '-  12' but to_char(-12, 'S9999') produces '  -12'. (The Oracle implementation does not allow the use of MI before 9, but rather requires that 9 precede MI.)

  • TH does not convert values less than zero and does not convert fractional numbers.

  • PL, SG, and TH are PostgreSQL extensions.

  • V with to_char multiplies the input values by 10^n, where n is the number of digits following V. V with to_number divides in a similar manner. to_char and to_number do not support the use of V combined with a decimal point (e.g., 99.9V99 is not allowed).

  • EEEE (scientific notation) cannot be used in combination with any of the other formatting patterns or modifiers other than digit and decimal point patterns, and must be at the end of the format string (e.g., 9.99EEEE is a valid pattern).

Certain modifiers can be applied to any template pattern to alter its behavior. For example, FM99.99 is the 99.99 pattern with the FM modifier. Table 9.27 shows the modifier patterns for numeric formatting.

Table 9.27. Template Pattern Modifiers for Numeric Formatting

Modifier Description Example
FM prefix fill mode (suppress trailing zeroes and padding blanks) FM99.99
TH suffix upper case ordinal number suffix 999TH
th suffix lower case ordinal number suffix 999th

Table 9.28 shows some examples of the use of the to_char function.

Table 9.28. to_char Examples

Expression Result
to_char(current_timestamp, 'Day, DD  HH12:MI:SS') 'Tuesday  , 06  05:39:18'
to_char(current_timestamp, 'FMDay, FMDD  HH12:MI:SS') 'Tuesday, 6  05:39:18'
to_char(-0.1, '99.99') '  -.10'
to_char(-0.1, 'FM9.99') '-.1'
to_char(-0.1, 'FM90.99') '-0.1'
to_char(0.1, '0.9') ' 0.1'
to_char(12, '9990999.9') '    0012.0'
to_char(12, 'FM9990999.9') '0012.'
to_char(485, '999') ' 485'
to_char(-485, '999') '-485'
to_char(485, '9 9 9') ' 4 8 5'
to_char(1485, '9,999') ' 1,485'
to_char(1485, '9G999') ' 1 485'
to_char(148.5, '999.999') ' 148.500'
to_char(148.5, 'FM999.999') '148.5'
to_char(148.5, 'FM999.990') '148.500'
to_char(148.5, '999D999') ' 148,500'
to_char(3148.5, '9G999D999') ' 3 148,500'
to_char(-485, '999S') '485-'
to_char(-485, '999MI') '485-'
to_char(485, '999MI') '485 '
to_char(485, 'FM999MI') '485'
to_char(485, 'PL999') '+485'
to_char(485, 'SG999') '+485'
to_char(-485, 'SG999') '-485'
to_char(-485, '9SG99') '4-85'
to_char(-485, '999PR') '<485>'
to_char(485, 'L999') 'DM 485'
to_char(485, 'RN') '        CDLXXXV'
to_char(485, 'FMRN') 'CDLXXXV'
to_char(5.2, 'FMRN') 'V'
to_char(482, '999th') ' 482nd'
to_char(485, '"Good number:"999') 'Good number: 485'
to_char(485.8, '"Pre:"999" Post:" .999') 'Pre: 485 Post: .800'
to_char(12, '99V999') ' 12000'
to_char(12.4, '99V999') ' 12400'
to_char(12.45, '99V9') ' 125'
to_char(0.0004859, '9.99EEEE') ' 4.86e-04'

This documentation is for an unsupported version of PostgreSQL.
You may want to view the same page for the
current
version, or one of the other supported versions listed above instead.

The PostgreSQL formatting functions provide a powerful set of tools for converting various data types (date/time, integer, floating point, numeric) to formatted strings and for converting from formatted strings to specific data types. Table 9.23 lists them. These functions all follow a common calling convention: the first argument is the value to be formatted and the second argument is a template that defines the output or input format.

Table 9.23. Formatting Functions

Function Return Type Description Example
to_char(timestamp, text) text convert time stamp to string to_char(current_timestamp, 'HH12:MI:SS')
to_char(interval, text) text convert interval to string to_char(interval '15h 2m 12s', 'HH24:MI:SS')
to_char(int, text) text convert integer to string to_char(125, '999')
to_char(double precision, text) text convert real/double precision to string to_char(125.8::real, '999D9')
to_char(numeric, text) text convert numeric to string to_char(-125.8, '999D99S')
to_date(text, text) date convert string to date to_date('05 Dec 2000', 'DD Mon YYYY')
to_number(text, text) numeric convert string to numeric to_number('12,454.8-', '99G999D9S')
to_timestamp(text, text) timestamp with time zone convert string to time stamp to_timestamp('05 Dec 2000', 'DD Mon YYYY')

Note

There is also a single-argument to_timestamp function; see Table 9.30.

Tip

to_timestamp and to_date exist to handle input formats that cannot be converted by simple casting. For most standard date/time formats, simply casting the source string to the required data type works, and is much easier. Similarly, to_number is unnecessary for standard numeric representations.

In a to_char output template string, there are certain patterns that are recognized and replaced with appropriately-formatted data based on the given value. Any text that is not a template pattern is simply copied verbatim. Similarly, in an input template string (for the other functions), template patterns identify the values to be supplied by the input data string.

Table 9.24 shows the template patterns available for formatting date and time values.

Table 9.24. Template Patterns for Date/Time Formatting

Pattern Description
HH hour of day (01-12)
HH12 hour of day (01-12)
HH24 hour of day (00-23)
MI minute (00-59)
SS second (00-59)
MS millisecond (000-999)
US microsecond (000000-999999)
SSSS seconds past midnight (0-86399)
AM, am, PM or pm meridiem indicator (without periods)
A.M., a.m., P.M. or p.m. meridiem indicator (with periods)
Y,YYY year (4 or more digits) with comma
YYYY year (4 or more digits)
YYY last 3 digits of year
YY last 2 digits of year
Y last digit of year
IYYY ISO 8601 week-numbering year (4 or more digits)
IYY last 3 digits of ISO 8601 week-numbering year
IY last 2 digits of ISO 8601 week-numbering year
I last digit of ISO 8601 week-numbering year
BC, bc, AD or ad era indicator (without periods)
B.C., b.c., A.D. or a.d. era indicator (with periods)
MONTH full upper case month name (blank-padded to 9 chars)
Month full capitalized month name (blank-padded to 9 chars)
month full lower case month name (blank-padded to 9 chars)
MON abbreviated upper case month name (3 chars in English, localized lengths vary)
Mon abbreviated capitalized month name (3 chars in English, localized lengths vary)
mon abbreviated lower case month name (3 chars in English, localized lengths vary)
MM month number (01-12)
DAY full upper case day name (blank-padded to 9 chars)
Day full capitalized day name (blank-padded to 9 chars)
day full lower case day name (blank-padded to 9 chars)
DY abbreviated upper case day name (3 chars in English, localized lengths vary)
Dy abbreviated capitalized day name (3 chars in English, localized lengths vary)
dy abbreviated lower case day name (3 chars in English, localized lengths vary)
DDD day of year (001-366)
IDDD day of ISO 8601 week-numbering year (001-371; day 1 of the year is Monday of the first ISO week)
DD day of month (01-31)
D day of the week, Sunday (1) to Saturday (7)
ID ISO 8601 day of the week, Monday (1) to Sunday (7)
W week of month (1-5) (the first week starts on the first day of the month)
WW week number of year (1-53) (the first week starts on the first day of the year)
IW week number of ISO 8601 week-numbering year (01-53; the first Thursday of the year is in week 1)
CC century (2 digits) (the twenty-first century starts on 2001-01-01)
J Julian Date (integer days since November 24, 4714 BC at local midnight; see Section B.7)
Q quarter
RM month in upper case Roman numerals (I-XII; I=January)
rm month in lower case Roman numerals (i-xii; i=January)
TZ upper case time-zone abbreviation (only supported in to_char)
tz lower case time-zone abbreviation (only supported in to_char)
OF time-zone offset from UTC (only supported in to_char)

Modifiers can be applied to any template pattern to alter its behavior. For example, FMMonth is the Month pattern with the FM modifier. Table 9.25 shows the modifier patterns for date/time formatting.

Table 9.25. Template Pattern Modifiers for Date/Time Formatting

Modifier Description Example
FM prefix fill mode (suppress leading zeroes and padding blanks) FMMonth
TH suffix upper case ordinal number suffix DDTH, e.g., 12TH
th suffix lower case ordinal number suffix DDth, e.g., 12th
FX prefix fixed format global option (see usage notes) FX Month DD Day
TM prefix translation mode (print localized day and month names based on lc_time) TMMonth
SP suffix spell mode (not implemented) DDSP

Usage notes for date/time formatting:

  • FM suppresses leading zeroes and trailing blanks that would otherwise be added to make the output of a pattern be fixed-width. In PostgreSQL, FM modifies only the next specification, while in Oracle FM affects all subsequent specifications, and repeated FM modifiers toggle fill mode on and off.

  • TM does not include trailing blanks. to_timestamp and to_date ignore the TM modifier.

  • to_timestamp and to_date skip multiple blank spaces in the input string unless the FX option is used. For example, to_timestamp('2000    JUN', 'YYYY MON') works, but to_timestamp('2000    JUN', 'FXYYYY MON') returns an error because to_timestamp expects one space only. FX must be specified as the first item in the template.

  • Ordinary text is allowed in to_char templates and will be output literally. You can put a substring in double quotes to force it to be interpreted as literal text even if it contains pattern key words. For example, in '"Hello Year "YYYY', the YYYY will be replaced by the year data, but the single Y in Year will not be. In to_date, to_number, and to_timestamp, double-quoted strings skip the number of input characters contained in the string, e.g., "XX" skips two input characters.

  • If you want to have a double quote in the output you must precede it with a backslash, for example '"YYYY Month"'.

  • In to_timestamp and to_date, if the year format specification is less than four digits, e.g., YYY, and the supplied year is less than four digits, the year will be adjusted to be nearest to the year 2020, e.g., 95 becomes 1995.

  • In to_timestamp and to_date, negative years are treated as signifying BC. If you write both a negative year and an explicit BC field, you get AD again. An input of year zero is treated as 1 BC.

  • In to_timestamp and to_date, the YYYY conversion has a restriction when processing years with more than 4 digits. You must use some non-digit character or template after YYYY, otherwise the year is always interpreted as 4 digits. For example (with the year 20000): to_date('200001131', 'YYYYMMDD') will be interpreted as a 4-digit year; instead use a non-digit separator after the year, like to_date('20000-1131', 'YYYY-MMDD') or to_date('20000Nov31', 'YYYYMonDD').

  • In to_timestamp and to_date, the CC (century) field is accepted but ignored if there is a YYY, YYYY or Y,YYY field. If CC is used with YY or Y then the result is computed as that year in the specified century. If the century is specified but the year is not, the first year of the century is assumed.

  • In to_timestamp and to_date, weekday names or numbers (DAY, D, and related field types) are accepted but are ignored for purposes of computing the result. The same is true for quarter (Q) fields.

  • In to_timestamp and to_date, an ISO 8601 week-numbering date (as distinct from a Gregorian date) can be specified in one of two ways:

    • Year, week number, and weekday: for example to_date('2006-42-4', 'IYYY-IW-ID') returns the date 2006-10-19. If you omit the weekday it is assumed to be 1 (Monday).

    • Year and day of year: for example to_date('2006-291', 'IYYY-IDDD') also returns 2006-10-19.

    Attempting to enter a date using a mixture of ISO 8601 week-numbering fields and Gregorian date fields is nonsensical, and will cause an error. In the context of an ISO 8601 week-numbering year, the concept of a month or day of month has no meaning. In the context of a Gregorian year, the ISO week has no meaning.

    Caution

    While to_date will reject a mixture of Gregorian and ISO week-numbering date fields, to_char will not, since output format specifications like YYYY-MM-DD (IYYY-IDDD) can be useful. But avoid writing something like IYYY-MM-DD; that would yield surprising results near the start of the year. (See Section 9.9.1 for more information.)

  • In to_timestamp, millisecond (MS) or microsecond (US) fields are used as the seconds digits after the decimal point. For example to_timestamp('12.3', 'SS.MS') is not 3 milliseconds, but 300, because the conversion treats it as 12 + 0.3 seconds. So, for the format SS.MS, the input values 12.3, 12.30, and 12.300 specify the same number of milliseconds. To get three milliseconds, one must write 12.003, which the conversion treats as 12 + 0.003 = 12.003 seconds.

    Here is a more complex example: to_timestamp('15:12:02.020.001230', 'HH24:MI:SS.MS.US') is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds + 1230 microseconds = 2.021230 seconds.

  • to_char(..., 'ID')‘s day of the week numbering matches the extract(isodow from ...) function, but to_char(..., 'D')‘s does not match extract(dow from ...)‘s day numbering.

  • to_char(interval) formats HH and HH12 as shown on a 12-hour clock, for example zero hours and 36 hours both output as 12, while HH24 outputs the full hour value, which can exceed 23 in an interval value.

Table 9.26 shows the template patterns available for formatting numeric values.

Table 9.26. Template Patterns for Numeric Formatting

Pattern Description
9 digit position (can be dropped if insignificant)
0 digit position (will not be dropped, even if insignificant)
. (period) decimal point
, (comma) group (thousands) separator
PR negative value in angle brackets
S sign anchored to number (uses locale)
L currency symbol (uses locale)
D decimal point (uses locale)
G group separator (uses locale)
MI minus sign in specified position (if number < 0)
PL plus sign in specified position (if number > 0)
SG plus/minus sign in specified position
RN Roman numeral (input between 1 and 3999)
TH or th ordinal number suffix
V shift specified number of digits (see notes)
EEEE exponent for scientific notation

Usage notes for numeric formatting:

  • 0 specifies a digit position that will always be printed, even if it contains a leading/trailing zero. 9 also specifies a digit position, but if it is a leading zero then it will be replaced by a space, while if it is a trailing zero and fill mode is specified then it will be deleted. (For to_number(), these two pattern characters are equivalent.)

  • The pattern characters S, L, D, and G represent the sign, currency symbol, decimal point, and thousands separator characters defined by the current locale (see lc_monetary and lc_numeric). The pattern characters period and comma represent those exact characters, with the meanings of decimal point and thousands separator, regardless of locale.

  • If no explicit provision is made for a sign in to_char()‘s pattern, one column will be reserved for the sign, and it will be anchored to (appear just left of) the number. If S appears just left of some 9‘s, it will likewise be anchored to the number.

  • A sign formatted using SG, PL, or MI is not anchored to the number; for example, to_char(-12, 'MI9999') produces '-  12' but to_char(-12, 'S9999') produces '  -12'. (The Oracle implementation does not allow the use of MI before 9, but rather requires that 9 precede MI.)

  • TH does not convert values less than zero and does not convert fractional numbers.

  • PL, SG, and TH are PostgreSQL extensions.

  • V with to_char multiplies the input values by 10^n, where n is the number of digits following V. V with to_number divides in a similar manner. to_char and to_number do not support the use of V combined with a decimal point (e.g., 99.9V99 is not allowed).

  • EEEE (scientific notation) cannot be used in combination with any of the other formatting patterns or modifiers other than digit and decimal point patterns, and must be at the end of the format string (e.g., 9.99EEEE is a valid pattern).

Certain modifiers can be applied to any template pattern to alter its behavior. For example, FM99.99 is the 99.99 pattern with the FM modifier. Table 9.27 shows the modifier patterns for numeric formatting.

Table 9.27. Template Pattern Modifiers for Numeric Formatting

Modifier Description Example
FM prefix fill mode (suppress trailing zeroes and padding blanks) FM99.99
TH suffix upper case ordinal number suffix 999TH
th suffix lower case ordinal number suffix 999th

Table 9.28 shows some examples of the use of the to_char function.

Table 9.28. to_char Examples

Expression Result
to_char(current_timestamp, 'Day, DD  HH12:MI:SS') 'Tuesday  , 06  05:39:18'
to_char(current_timestamp, 'FMDay, FMDD  HH12:MI:SS') 'Tuesday, 6  05:39:18'
to_char(-0.1, '99.99') '  -.10'
to_char(-0.1, 'FM9.99') '-.1'
to_char(-0.1, 'FM90.99') '-0.1'
to_char(0.1, '0.9') ' 0.1'
to_char(12, '9990999.9') '    0012.0'
to_char(12, 'FM9990999.9') '0012.'
to_char(485, '999') ' 485'
to_char(-485, '999') '-485'
to_char(485, '9 9 9') ' 4 8 5'
to_char(1485, '9,999') ' 1,485'
to_char(1485, '9G999') ' 1 485'
to_char(148.5, '999.999') ' 148.500'
to_char(148.5, 'FM999.999') '148.5'
to_char(148.5, 'FM999.990') '148.500'
to_char(148.5, '999D999') ' 148,500'
to_char(3148.5, '9G999D999') ' 3 148,500'
to_char(-485, '999S') '485-'
to_char(-485, '999MI') '485-'
to_char(485, '999MI') '485 '
to_char(485, 'FM999MI') '485'
to_char(485, 'PL999') '+485'
to_char(485, 'SG999') '+485'
to_char(-485, 'SG999') '-485'
to_char(-485, '9SG99') '4-85'
to_char(-485, '999PR') '<485>'
to_char(485, 'L999') 'DM 485'
to_char(485, 'RN') '        CDLXXXV'
to_char(485, 'FMRN') 'CDLXXXV'
to_char(5.2, 'FMRN') 'V'
to_char(482, '999th') ' 482nd'
to_char(485, '"Good number:"999') 'Good number: 485'
to_char(485.8, '"Pre:"999" Post:" .999') 'Pre: 485 Post: .800'
to_char(12, '99V999') ' 12000'
to_char(12.4, '99V999') ' 12400'
to_char(12.45, '99V9') ' 125'
to_char(0.0004859, '9.99EEEE') ' 4.86e-04'

Функции форматирования PostgreSQL предоставляют мощный набор инструментов для преобразования различных типов данных (дата/время, целые числа, числа с плавающей запятой) в форматированные строки и для преобразования форматированных строк в определенные типы данных. В таблице 9.26 они перечислены. Все эти функции следуют общему соглашению о вызовах: первый аргумент — это форматируемое значение, а второй аргумент — это шаблон, определяющий выходной или входной формат.

В to_char выходного шаблона to_char есть определенные шаблоны, которые распознаются и заменяются соответствующим образом отформатированными данными на основе заданного значения. Любой текст, не являющийся шаблоном, просто копируется дословно. Точно так же в строке входного шаблона (для других функций) шаблоны шаблона идентифицируют значения, которые должны быть предоставлены строкой входных данных. Если в строке шаблона есть символы, которые не являются шаблонами шаблона, соответствующие символы в строке входных данных просто пропускаются (независимо от того, равны ли они символам строки шаблона).

В Табл. 9.27 показаны шаблоны шаблонов, доступные для форматирования значений даты и времени.

Модификаторы могут быть применены к любому шаблону шаблона, чтобы изменить его поведение. Например, FMMonth — это шаблон Month с модификатором FM .В Табл. 9.28 показаны шаблоны модификаторов для форматирования даты/времени.

  • FM подавляет начальные нули и конечные пробелы, которые в противном случае были бы добавлены, чтобы сделать вывод шаблона фиксированной шириной. В PostgreSQL FM изменяет только следующую спецификацию, в то время как в Oracle FM влияет на все последующие спецификации, а повторяющиеся модификаторы FM включают и выключают режим заполнения.

  • TM подавляет завершающие пробелы независимо от того, указан FM или нет .

  • to_timestamp и to_date игнорируют регистр букв во вводе; так, например, MON , Mon и mon принимают одни и те же строки. При использовании модификатора TM сворачивание регистра выполняется в соответствии с правилами сортировки входных данных функции (см. Раздел 24.2 ).

  • to_timestamp и to_date пропускают несколько пробелов в начале входной строки и вокруг значений даты и времени, если не используется опция FX .Например, to_timestamp(' 2000 JUN', 'YYYY MON') и to_timestamp('2000 - JUN', 'YYYY-MON') работают, но to_timestamp('2000 JUN', 'FXYYYY MON') возвращает ошибку, потому что to_timestamp ожидает только один пробел. FX должен быть указан первым элементом в шаблоне.

  • Разделитель (пробел или to_timestamp / нецифровой символ) в строке шаблона to_timestamp и to_date соответствует любому одиночному разделителю во входной строке или пропускается, если не используется опция FX . Например, to_timestamp('2000JUN', 'YYYY///MON') и to_timestamp('2000/JUN', 'YYYY MON') работают, но to_timestamp('2000//JUN', 'YYYY/MON') возвращает ошибка, потому что количество разделителей во входной строке превышает количество разделителей в шаблоне.

    Если указано FX , разделитель в строке шаблона соответствует ровно одному символу во входной строке. Но обратите внимание, что символ входной строки не обязательно должен совпадать с разделителем строки шаблона. Например, to_timestamp('2000/JUN', 'FXYYYY MON') работает, но to_timestamp('2000/JUN', 'FXYYYY MON') возвращает ошибку, потому что второй пробел в строке шаблона использует букву J из ввода нить.

  • Шаблон шаблона TZH может соответствовать числу со знаком.Без опции FX знаки «минус» могут быть неоднозначными и интерпретироваться как разделители. Эта неоднозначность разрешается следующим образом: если количество разделителей перед TZH в строке шаблона меньше, чем количество разделителей перед знаком минус во входной строке, знак минус интерпретируется как часть TZH . В противном случае знак минус считается разделителем между значениями. Например, to_timestamp('2000 -10', 'YYYY TZH') соответствует -10 для TZH , но to_timestamp('2000 -10', 'YYYY TZH') соответствует 10 для TZH .

  • Обычный текст разрешен в шаблонах to_char и будет выводиться буквально. Вы можете заключить подстроку в двойные кавычки, чтобы заставить ее интерпретироваться как буквальный текст, даже если она содержит шаблоны шаблонов. Например, в '"Hello Year "YYYY' , то YYYY будет заменен данными года, но единственный Y в Year не будет. В to_date , to_number и to_timestamp буквальный текст и строки в двойных кавычках приводят к пропуску количества символов, содержащихся в строке; например, "XX" пропускает два входных символа (независимо от того, являются они XX или нет ).

    Tip

    До PostgreSQL 12 можно было пропускать произвольный текст во входной строке, используя небуквенные или нецифровые символы. Например, to_timestamp('2000y6m1d', 'yyyy-MM-DD') раньше работало. Теперь для этой цели можно использовать только буквенные символы. Например, to_timestamp('2000y6m1d', 'yyyytMMtDDt') и to_timestamp('2000y6m1d', 'yyyy"y"MM"m"DD"d"') пропускают y , m и d .

  • Если вы хотите, чтобы в выводе были двойные кавычки, вы должны поставить перед ним обратную косую черту, например '"YYYY Month"' . Обратные косые черты не являются чем-то особенным, кроме строк в двойных кавычках. Внутри строки, заключенной в двойные кавычки, обратная косая черта приводит к тому, что следующий символ воспринимается буквально, каким бы он ни был (но это не имеет особого эффекта, если следующий символ не является двойной кавычкой или другой обратной косой чертой).

  • В to_timestamp и to_date , если спецификация формата года меньше четырех цифр, например, YYY , а предоставленный год меньше четырех цифр, год будет скорректирован так, чтобы он был ближайшим к 2020 году, например, 95 становится 1995.

  • В to_timestamp и to_date отрицательные годы рассматриваются как обозначающие BC. Если вы напишете и отрицательный год, и явное поле BC , вы снова получите AD. Вход нулевого года рассматривается как 1 год до н.э.

  • В to_timestamp и to_date , то YYYY преобразование имеет ограничение при обработке лет с более чем 4 -х цифр. Вы должны использовать какой-либо нецифровой символ или шаблон после YYYY , иначе год всегда интерпретируется как 4 цифры. Например (с годом 20000): to_date('200001131', 'YYYYMMDD') будет интерпретироваться как год из 4 цифр; вместо этого используйте нецифровой разделитель после года, например to_date('20000-1131', 'YYYY-MMDD') или to_date('20000Nov31', 'YYYYMonDD') .

  • В to_timestamp и to_date поле CC (век) принимается, но игнорируется, если есть поле YYY , YYYY или Y,YYY . Если CC используется с YY или Y , то результат вычисляется как год в указанном столетии. Если указан век, а год нет, предполагается, что это первый год века.

  • В to_timestamp и to_date имена или числа дней недели ( DAY , D и связанные типы полей) принимаются, но игнорируются для целей вычисления результата. То же самое и с четвертью ( Q ) полей.

  • В to_timestamp и to_date дата нумерации недель ISO 8601 (в отличие от даты по григорианскому календарю ) может быть указана одним из двух способов:

    • Год, номер недели и день недели: например, to_date('2006-42-4', 'IYYY-IW-ID') возвращает дату 2006-10-19 . Если вы не укажете день недели, он будет равен 1 (понедельник).

    • Год и день года: например, to_date('2006-291', 'IYYY-IDDD') также возвращает 2006-10-19 .

    Попытка ввести дату,используя смесь полей недельной нумерации ISO 8601 и григорианской даты,является бессмысленной и приведет к ошибке.В контексте года с нумерацией недель ISO 8601 понятие «месяц» или «день месяца» не имеет смысла.В контексте григорианского года неделя ISO не имеет никакого значения.

  • In this guide, you’ll learn how to format DATE values into many different formats, how to insert DATE values into a table, and more.

    Summary

    You can insert date values into a DATE column in Postgres in many different formats, but the recommended format is the ISO format of YYYY-MM-DD.

    You can format dates in Postgres when you display them using the TO_CHAR function, such as TO_CHAR(order_date, ‘MM-DD-YYYY’).

    Postgres Date Data Type

    We’ll be working with the DATE data type in this guide.

    The DATE data type in Postgres captures the date without the time component.

    There is a range of values it can store: from 4,713 BC to 5,874,897 AD.

    To define a column with the DATE data type, simply specify the data type:

    CREATE TABLE cust_order (
      order_id INT,
      order_date DATE
    );

    The order_date column is stored as a DATE value.

    Let’s insert some data into this table.

    You can find all of the SQL scripts used in this guide in my GitHub repository.

    Insert a Date into a Table

    In many other databases, you have to insert date values using a certain default format, or use a function to convert your input format into the required format.

    However, in Postgres, you can insert date data in many different types, and it will work.

    The recommended format is the one that meets the ISO 8601 standard, which is YYYY-MM-DD.

    Here are a few examples of inserting data into a DATE column in Postgres.

    INSERT INTO cust_order (order_id, order_date) VALUES (1, '2022-10-13');
    INSERT INTO cust_order (order_id, order_date) VALUES (2, '14-OCT-2022');
    INSERT INTO cust_order (order_id, order_date) VALUES (3, '20221015');

    All three of these rows should be inserted without issues.

    However, we can try to run this statement:

    INSERT INTO cust_order (order_id, order_date) VALUES (4, '16-10-2022');

    We’ll get an error:

    ERROR:  date/time field value out of range: "16-10-2022"
    LINE 1: ...INTO cust_order (order_id, order_date) VALUES (4, '16-10-202...
                                                                 ^
    HINT:  Perhaps you need a different "datestyle" setting.
    SQL state: 22008
    Character: 58

    This happens because the format we have specified is not clear to the database which field is the day and which is the month. We know by looking at it that 16 is the day because there is no month number of 16.

    However, the database doesn’t know this.

    A way around this, as mentioned by the hint in the error message, is to use a different DateStyle setting. You can find out more in the Postgres documentation here.

    We can select from this table and see the results.

    SELECT order_id, order_date
    FROM cust_order;

    Results:

    order_id order_date
    1 2022-10-13
    2 2022-10-14
    3 2022-10-15

    The three rows that were inserted are shown here.

    Display a Date in a Certain Format Using TO_CHAR

    When we select a DATE column from our table, we can see the format that is shown:

    SELECT order_id, order_date
    FROM cust_order;

    Results:

    order_id order_date
    1 2022-10-13
    2 2022-10-14
    3 2022-10-15

    The format of the date value is YYYY-MM-DD.

    What if we want to show it in a different format?

    You can use the TO_CHAR function in Postgres.

    The TO_CHAR function looks like this:

    TO_CHAR (date_value, output_format)

    The parameters are:

    • date_value: the value you want to display in a different format.
    • output_format: the format to display

    The output_format must be in single quotes and uses the patterns in the table below.

    For example, a value in your function of YYYY will be replaced with the four-digit year when it is displayed.

    This is the list of output format values that apply to dates.

    Pattern Description
    Y,YYY year (4 or more digits) with a comma
    YYYY year (4 or more digits)
    YYY last 3 digits of year
    YY last 2 digits of year
    Y last digit of year
    IYYY ISO 8601 week-numbering year
    IYY last 3 digits of ISO 8601 week-numbering year
    IY last 2 digits of ISO 8601 week-numbering year
    I last digit of ISO 8601 week-numbering year
    BC, bc, AD, or ad era indicator without periods
    B.C., b.c., A.D. or a.d. era indicator with periods
    MONTH full upper case month name (blank-padded to 9 characters)
    Month full capitalised month name (blank-padded to 9 characters)
    month full lower case month name (blank-padded to 9 characters)
    MON abbreviated upper case month name
    Mon abbreviated capitalised month name
    mon abbreviated lower case month name
    MM month number (01-12)
    DAY full upper case day name (blank-padded to 9 characters)
    Day full capitalised day name (blank-padded to 9 characters)
    day full lower case day name (blank-padded to 9 characters)
    DY abbreviated upper case day name (blank-padded to 9 characters)
    Dy abbreviated capitalised day name (blank-padded to 9 characters)
    dy abbreviated lower case day name (blank-padded to 9 characters)
    DDD day of year (001-366)
    IDDD day of ISO 8601 week-numbering year (001-371). Day 1 of the year is Monday of the first ISO week
    DD day of month (01-31)
    D day of the week, Sunday (1) to Saturday (7)
    ID ISO 8601 day of the week, Monday (1) to Sunday (7)
    W week of the month (1-5). The first week starts on the first day of the month
    WW week number of the year (1-53). The first week starts on the first day of the year
    IW week number of ISO 8601 week-numbering year (01-53). The first Thursday of the year is in week 1.
    CC 2 digit century (the 21st century starts on 2001-01-01)
    J Julian Date (number of days since Nov 24, 4714 BC)
    Q quarter
    RM month in upper case Roman numerals (I-XII, I=January)
    rm month in lower case Roman numerals (i-xii, i=January)

    Let’s see some examples.

    Example 1 – DD/MM/YYYY

    Here’s an example of formatting dates in the DD/MM/YYYY format.

    SELECT
    order_date, 
    TO_CHAR(order_date, 'DD/MM/YYYY') AS formatted_date
    FROM cust_order;

    Results:

    order_date formatted_date
    2022-10-13 13/10/2022
    2022-10-14 14/10/2022
    2022-10-15 15/10/2022

    Example 2 – Names

    Here’s an example using the names of days and months. We’ve also added two examples of the same part of the date: the Day (name of the day) and DD (day number).

    SELECT
    order_date, 
    TO_CHAR(order_date, 'Day, DD Month, YYYY') AS formatted_date
    FROM cust_order;

    Results:

    order_date formatted_date
    2022-10-13 Thursday, 13 October, 2022
    2022-10-14 Friday, 14 October, 2022
    2022-10-15 Saturday, 15 October, 2022

    We can see the name of the day, the date, the month name, and the year.

    Example 3 – Other Attributes

    Here’s an example of getting other attributes of the date.

    SELECT
    order_date, 
    TO_CHAR(order_date, 'MM') AS month_num,
    TO_CHAR(order_date, 'DDD') AS day_of_year,
    TO_CHAR(order_date, 'ID') AS day_of_week,
    TO_CHAR(order_date, 'WW') AS week_of_year,
    TO_CHAR(order_date, 'J') AS julian_date
    FROM cust_order;

    Results:

    order_date month _num day_of _year day_of _week week_of _year julian _date
    2022-10-13 10 286 4 41 2459866
    2022-10-14 10 287 5 41 2459867
    2022-10-15 10 288 6 42 2459868

    We can see a few different attributes of the date values here.

    Frequently Asked Questions

    How do I convert a date to a string in PostgreSQL?

    You can use the TO_CHAR function to convert a date value to a string. The output of this function is a string.

    As shown in the examples above, you can define the output format however you like.

    How do I convert a datetime to a date in PostgreSQL?

    To convert a DATETIME to a DATE (or remove the time component), you can either use the DATE function or the ::DATE operator.

    You can enclose your DATETIME within the DATE function. Or, you can add ::DATE after the DATETIME value.

    Here’s an example using the NOW() function, which returns the current date and time in a DATETIME format.

    SELECT
    NOW(),
    NOW()::DATE,
    DATE(NOW());

    Results:

    now now date
    2022-10-13 18:28:10.356797+11 2022-10-13 2022-10-13

    We can see in the second and third columns that the time component is removed.

    Conclusion

    Formatting a date in Postgres can be done using the TO_CHAR function which is quite flexible. You can also insert date values using a range of formats, but the recommended format is the ISO format of YYYY-MM-DD.

    In this PostgreSQL tutorial, we will learn about PostgreSQL DATE Format with a few examples. We use the DATE data type in PostgreSQL to store DATE type values in a table. PostgreSQL supports many DATE Formats, and we will learn each one of them in detail. By the end of this tutorial, you will have complete knowledge of the PostgreSQL DATE Format.

    • PostgreSQL DATE Format
    • Postgresql date format functions
    • PostgreSQL DATE Format INSERT
    • PostgreSQL DATE Format WHERE Clause
    • PostgreSQL DATE Format yyyymmdd
    • PostgreSQL DATE Format mm/dd/yyyy
    • PostgreSQL DATE Format dd/mm/yyyy
    • PostgreSQL date format yyyy-mm
    • PostgreSQL date format month name
    • PostgreSQL DATE Format dd/mm/yyyy hh mm
    • PostgreSQL DATE Format With Timezone
    • PostgreSQL DATE Format 24 Hour
    • Postgresql date format yyyy-mm
    • Postgresql date format convert

    In this section, we will learn about PostgreSQL DATE Format. We use the DATE data type in PostgreSQL to store DATE type values in a table. PostgreSQL assigns 4 bytes of storage to a DATE value. The highest and the lowest value that can be stored in PostgreSQL DATE data type are 5874897 AD and 4713 BC.

    PostgreSQL stores the DATE type values in YYYY-MM-DD format. The date can be inserted in many formats such as YYYY-MM-DD, YY-MM-DD, MM-DD-YYYY, etc. We will look at an example of how to define a DATE type column.

    First, connect to the database in PostgreSQL using the c command and the name of the database:

    c sqlserverguides

    Now create a table in PostgreSQL using these lines of code having a column with DATE data type:

    CREATE TABLE Employee(
    Emp_ID integer NOT NULL PRIMARY KEY,
    Name text NOT NULL,
    Dept text,
    Salary money,
    Date_Of_Joining DATE);
    PostgreSQL DATE Format
    PostgreSQL- Create Table DATE Format

    Here we have created a column named Date_Of _Joining having DATE data type.

    Now we will insert some data in this table using the PostgreSQL INSERT statement, and we will use the YYYY-MM-DD format to INSERT the Date_Of_Joining:

    INSERT INTO Employee VALUES(1,'James','IT',3500,'2016-05-25');
    INSERT INTO Employee VALUES(2,'Simona','Electrical',2500,'2018-08-12');
    INSERT INTO Employee VALUES(3,'Kiley','Mechanical',2250,'2019-10-21');
    INSERT INTO Employee VALUES(4,'Fletcher','IT',3000,'2017-06-10');
    INSERT INTO Employee VALUES(5,'Alisha','IT',2700,'2018-9-16');
    INSERT INTO Employee VALUES(6,'Chanel','Mechanical',2500,'2018-12-07');
    INSERT INTO Employee VALUES(7,'Erick','IT',3250,'2017-07-13');
    INSERT INTO Employee VALUES(8,'Amber','Electrical',2700,'2018-03-05');
    INSERT INTO Employee VALUES(9,'Stephen','Electrical',2000,'2020-11-24');
    INSERT INTO Employee VALUES(10,'Jose','HR',3700,'2016-01-23');
    PostgreSQL DATE Format example
    PostgreSQL- INSERT DATA DATE Format

    We INSERT the DATE inside single quotation marks as shown in the screenshot.

    We have successfully entered the data which can be checked by using the SELECT statement in PostgreSQL:

    SELECT * 
    FROM Employee;
    PostgreSQL DATE Format tutorial
    PostgreSQL DATA Inserted Successfully DATE Format

    In this section, we learned about PostgreSQL DATE Format.

    Read How to create a table in PostgreSQL [Terminal + pgAdmin]

    PostgreSQL date format functions

    to_char( ): It is a function that helps in giving the output of a Postgres date value in a specified format. This function accepts the following two parameters.

    • Input date: It is the date that we want to convert into a specific format.
    • Date format: It is the way we specify the new date format.

    Syntax: to_char(expression, format)

    Template pattern supported by Date formatting:

    Meaning of Pattern Pattern
    To get a year in four digits YYYY
    To get the last three digits of a year YYY
    To get the last two digits of a year YY
    To show month name in capital letters MONTH
    To show month name with the first letter capitalized Month
    To show month name in lowercase letters month
    Month abbreviation in all capital, the first letter capitalized, and all lowercase letters, respectively MON/Mon/mon
    To show month number (1-12) MM
    Day name in all capital, first letter capitalized, and all lowercase letters, respectively DAY/Day/day
    To get the day of the year (001 to 366) DDD
    To get the day of the month (01 to 31) DD
    To get the day of the week (Sunday (1) to Saturday (7)) D
    To get a week of the month W
    To show the week of the year WW

    to_date( ): It is a function that can be used to convert string to date and its return type is the date.

    syntax: to_date(text,text)

    SELECT to_date('04 Jan 2021', 'DD Mon YYYY');

    From the above code, we are converting string ’04 Jan 2021′ to date ‘2020-01-04’.

    Postgresql date format functions
    Postgresql date format functions
    • now( ): It is used to get the current dates with timezone.
    • typecast (::): It is an operator that we use to cast from one data type to another. Here we will use for casting DateTime value to date value.

    PostgreSQL DATE Format INSERT

    In this section, we will learn about PostgreSQL DATE Format INSERT, i.e., how to insert DATE type values in a PostgreSQL table. There are many DATE formats that can be used to insert data in a PostgreSQL table and we will learn about some of the DATE formats in the subsequent sections.

    In this section, we will look at an example of the Month DD, YYYY format.

    First, connect to the database in PostgreSQL using the c command and the name of the database:

    c sqlserverguides

    Now create a table in PostgreSQL using these lines of code having a column with DATE data type:

    CREATE TABLE Employee(
    Emp_ID integer NOT NULL PRIMARY KEY,
    Name text NOT NULL,
    Dept text,
    Salary money,
    Date_Of_Joining DATE);

    PostgreSQL DATE Format INSERT

    PostgreSQL- Create Table DATE Format

    Now we will insert some data in this table using the PostgreSQL INSERT statement, and we will use the Month DD, YYYY format to INSERT the Date_Of_Joining:

    INSERT INTO Employee VALUES(1,'James','IT',3500,'May 25, 2016');
    INSERT INTO Employee VALUES(2,'Simona','Electrical',2500,'August 12, 2018');
    INSERT INTO Employee VALUES(3,'Kiley','Mechanical',2250,'October 21, 2019');
    INSERT INTO Employee VALUES(4,'Fletcher','IT',3000,'June 10, 2017');
    INSERT INTO Employee VALUES(5,'Alisha','IT',2700,'September 16, 2018');
    INSERT INTO Employee VALUES(6,'Chanel','Mechanical',2500,'December 07, 2018');
    INSERT INTO Employee VALUES(7,'Erick','IT',3250,'July 13, 2017');
    INSERT INTO Employee VALUES(8,'Amber','Electrical',2700,'March 05, 2018');
    INSERT INTO Employee VALUES(9,'Stephen','Electrical',2000,'November 24, 2020');
    INSERT INTO Employee VALUES(10,'Jose','HR',3700,'January 23, 2016');

    PostgreSQL Insert DATA DATE MDY

    PostgreSQL- Insert DATA DATE MDY Format

    We have inserted the DATE type values in Month DD, YYYY format inside single quotation marks.

    We have successfully entered the data which can be checked by using the SELECT statement in PostgreSQL:

    SELECT * 
    FROM Employee;
    PostgreSQL DATE Format INSERT to table
    PostgreSQL DATA Inserted Successfully DATE Format

    It is clear from the screenshot that PostgreSQL stores the DATE type in YYYY-MM-DD format even if we insert it in any format.

    In this section, we learned about PostgreSQL DATE Format INSERT.

    Another Example:

    In Postgresql, we can insert the Date in a different format in a table, let’s understand through an example.

    Create a table named date_format.

    CREATE TABLE date_format(new_date date);

    In the above code, we are creating a table named date_format with column new_date that is going to contains the date in a different format.

    Insert the following records.

    INSERT INTO date_format(new_date)VALUES(to_date('2021 Jan 10','YYYY Mon DD'));
    
    INSERT INTO date_format(new_date)VALUES(to_date('2021/01/10','YYYY/MM/DD'));
    
    INSERT INTO date_format(new_date)VALUES(to_date('2021-01-10','YYYY-MM-DD'));

    from the above code, we are adding data in different formats, but Postgresql will store in format YYYY-MM-DD.

    The output of the above code is given below.

    Postgresql date format insert
    Postgresql date format insert

    This is an example of a PostgreSQL date format insert.

    Read PostgreSQL installation on Linux step by step

    PostgreSQL DATE Format WHERE Clause

    In this section, we will learn about PostgreSQL DATE Format WHERE Clause. We can use the DATE type column with WHERE clause in PostgreSQL to filter data according to a condition. We will look at an example where we will filter data using the WHERE clause in PostgreSQL having a DATE data type.

    First, connect to the database in PostgreSQL using the c command and the name of the database:

    c sqlserverguides

    Now create a table in PostgreSQL using these lines of code having a column with DATE data type:

    CREATE TABLE Employee(
    Emp_ID integer NOT NULL PRIMARY KEY,
    Name text NOT NULL,
    Dept text,
    Salary money,
    Date_Of_Joining DATE);
    PostgreSQL DATE Format WHERE Clause
    PostgreSQL- Create Table DATE Format

    Here we have created a column named Date_Of _Joining having DATE data type.

    Now we will insert some data in this table using the PostgreSQL INSERT statement, and we will use the YYYY-MM-DD format to INSERT the Date_Of_Joining:

    INSERT INTO Employee VALUES(1,'James','IT',3500,'2016-05-25');
    INSERT INTO Employee VALUES(2,'Simona','Electrical',2500,'2018-08-12');
    INSERT INTO Employee VALUES(3,'Kiley','Mechanical',2250,'2019-10-21');
    INSERT INTO Employee VALUES(4,'Fletcher','IT',3000,'2017-06-10');
    INSERT INTO Employee VALUES(5,'Alisha','IT',2700,'2018-9-16');
    INSERT INTO Employee VALUES(6,'Chanel','Mechanical',2500,'2018-12-07');
    INSERT INTO Employee VALUES(7,'Erick','IT',3250,'2017-07-13');
    INSERT INTO Employee VALUES(8,'Amber','Electrical',2700,'2018-03-05');
    INSERT INTO Employee VALUES(9,'Stephen','Electrical',2000,'2020-11-24');
    INSERT INTO Employee VALUES(10,'Jose','HR',3700,'2016-01-23');
    PostgreSQL INSERT DATA DATE
    PostgreSQL- INSERT DATA DATE Format

    We INSERT the DATE inside single quotation marks as shown in the screenshot.

    We have successfully entered the data which can be checked by using the SELECT statement in PostgreSQL:

    SELECT *
    FROM Employee;
    PostgreSQL DATE Format WHERE Clause example
    PostgreSQL- DATA Inserted Successfully DATE Format

    Now we will use the WHERE clause in SELECT statement to filter data according to DATE date type:

    SELECT *
    FROM Employee
    WHERE Date_Of_Joining > '2018-01-01'; 
    PostgreSQL WHERE DATE
    PostgreSQL- WHERE Clause DATE Format

    In this example, we have filtered out the data of those employees who have joined the company after ‘ 2018-01-01 ‘.

    In this section, we learned about PostgreSQL DATE Format WHERE clause.

    Another Example:

    In Postgresql, we can format the date using the WHERE clause for a certain range of dates.

    Let’s run the below code to format the date in pattern YYYY/MM/DD.

    SELECT product_id,to_char(expiry_date,'YYY/MM/DD') FROM date_days
    WHERE product_id BETWEEN 2 AND 5;

    In the above code, we are showing the date in different formats like YYYY/MM/DD in the SELECT statement for product_id from 2 to 5 using the WHERE clause.

    The output of the above code is given below.

    Postgresql date format where clause
    Postgresql date format where clause

    This is an example of Postgresql date format where clause.

    Read How to connect to PostgreSQL database

    PostgreSQL DATE Format yyyymmdd

    In this section, we will learn about PostgreSQL DATE Format YYYYMMDD. We know that we can insert DATE in various formats such as YYYY-MM-DD, YY-MM-DD, MM-DD-YYYY, YYYYMMDD, etc. So we will look at an example where we will use the YYYYMMDD format to insert a DATE type value in PostgreSQL.

    First, connect to the database in PostgreSQL using the c command and the name of the database:

    c sqlserverguides

    Now create a table in PostgreSQL using these lines of code having a column with DATE data type:

    CREATE TABLE Employee(
    Emp_ID integer NOT NULL PRIMARY KEY,
    Name text NOT NULL,
    Dept text,
    Salary money,
    Date_Of_Joining DATE);
    PostgreSQL DATE Format yyyymmdd
    PostgreSQL- Create Table DATE Format

    Here we have created a column named Date_Of _Joining having DATE data type.

    Now we will insert some data in this table using the PostgreSQL INSERT statement, and we will use the YYYYMMDD format to INSERT the Date_Of_Joining:

    INSERT INTO Employee VALUES(1,'James','IT',3500,'20160525');
    INSERT INTO Employee VALUES(2,'Simona','Electrical',2500,'20180812');
    INSERT INTO Employee VALUES(3,'Kiley','Mechanical',2250,'20191021');
    INSERT INTO Employee VALUES(4,'Fletcher','IT',3000,'20170610');
    INSERT INTO Employee VALUES(5,'Alisha','IT',2700,'20180916');
    INSERT INTO Employee VALUES(6,'Chanel','Mechanical',2500,'20181207');
    INSERT INTO Employee VALUES(7,'Erick','IT',3250,'20170713');
    INSERT INTO Employee VALUES(8,'Amber','Electrical',2700,'20180305');
    INSERT INTO Employee VALUES(9,'Stephen','Electrical',2000,'20201124');
    INSERT INTO Employee VALUES(10,'Jose','HR',3700,'20160123');
    PostgreSQL DATE Format yyyymmdd example
    PostgreSQL Insert DATA DATE YMD Format

    We have inserted the DATE type values in YYYYMMDD format inside single quotation marks.

    We have successfully entered the data which can be checked by using the SELECT statement in PostgreSQL:

    SELECT *
    FROM Employee;
    PostgreSQL DATE Format yyyymmdd
    PostgreSQL DATA Inserted Successfully DATE Format

    It is clear from the screenshot that PostgreSQL stores the DATE type values in YYYY-MM-DD format irrespective of any format used while inserting the same, in this case, we used YYYYMMDD format to insert DATE type values and PostgreSQL stored it in YYYY-MM-DD format.

    In this section, we learned about PostgreSQL DATE Format YYYYMMDD.

    Read How to Uninstall PostgreSQL (Linux, Mac, and Windows)

    PostgreSQL DATE Format mm/dd/yyyy

    In this section, we will learn about PostgreSQL DATE Format MM/DD/YYYY. As we know that DATE type values can be inserted in many formats such as YYYY-MM-DD, YY-MM-DD, MM-DD-YYYY, MM/DD/YYYY, etc. So we will look at an example of PostgreSQL DATE MM/DD/YYYY format.

    First, connect to the database in PostgreSQL using the c command and the name of the database:

    c sqlserverguides

    Now create a table in PostgreSQL using these lines of code having a column with DATE data type:

    CREATE TABLE Employee(
    Emp_ID integer NOT NULL PRIMARY KEY,
    Name text NOT NULL,
    Dept text,
    Salary money,
    Date_Of_Joining DATE);

    PostgreSQL DATE Format mm/dd/yyyy

    PostgreSQL- Create Table DATE Format

    Here we have created a column named Date_Of _Joining having DATE data type.

    Now we will insert some data in this table using the PostgreSQL INSERT statement, and we will use the MM/DD/YYYY format to INSERT the Date_Of_Joining:

    INSERT INTO Employee VALUES(1,'James','IT',3500,'05/25/2016');
    INSERT INTO Employee VALUES(2,'Simona','Electrical',2500,'08/12/2018');
    INSERT INTO Employee VALUES(3,'Kiley','Mechanical',2250,'10/21/2019');
    INSERT INTO Employee VALUES(4,'Fletcher','IT',3000,'06/10/2017');
    INSERT INTO Employee VALUES(5,'Alisha','IT',2700,'09/16/2018');
    INSERT INTO Employee VALUES(6,'Chanel','Mechanical',2500,'12/07/2018');
    INSERT INTO Employee VALUES(7,'Erick','IT',3250,'07/13/2017');
    INSERT INTO Employee VALUES(8,'Amber','Electrical',2700,'03/05/2018');
    INSERT INTO Employee VALUES(9,'Stephen','Electrical',2000,'11/24/2020');
    INSERT INTO Employee VALUES(10,'Jose','HR',3700,'01/23/2016');
    PostgreSQL DATE Format mm/dd/yyyy example
    PostgreSQL- Insert Data MDY DATE Format

    We have inserted the DATE type values in YYYYMMDD format inside single quotation marks.

    We have successfully entered the data which can be checked by using the SELECT statement in PostgreSQL:

    SELECT *
    FROM Employee;
    DATE Format mm/dd/yyyy in PostgreSQL
    PostgreSQL DATA Inserted Successfully DATE Format

    It is clear from the screenshot that PostgreSQL stores the DATE type values in YYYY-MM-DD format irrespective of any format used while inserting the same, in this case, we used MM/DD/YYYY format to insert DATE type values and PostgreSQL stored it in YYYY-MM-DD format.

    In this section, we learned about PostgreSQL DATE Format MM/DD/YYYY.

    Read How to Restart PostgreSQL

    PostgreSQL DATE Format dd/mm/yyyy

    In this section, we will learn about PostgreSQL DATE Format DD/MM/YYYY. As we know that DATE type values can be inserted in many formats such as YYYY-MM-DD, YY-MM-DD, MM-DD-YYYY, etc.

    PostgreSQL does not support DD/MM/YYYY input format for the DATE data type. There is an alternative format DD-Month-YYYY where we can specify the DATE type values in DMY format, eg., 23-Dec-2016 So we will look at an example of PostgreSQL DATE DD-Month-YYYY format.

    First, connect to the database in PostgreSQL using the c command and the name of the database:

    c sqlserverguides

    Now create a table in PostgreSQL using these lines of code having a column with DATE data type:

    CREATE TABLE Employee(
    Emp_ID integer NOT NULL PRIMARY KEY,
    Name text NOT NULL,
    Dept text,
    Salary money,
    Date_Of_Joining DATE);
    PostgreSQL DATE Format dd/mm/yyyy
    PostgreSQL- Create Table DATE Format

    Here we have created a column named Date_Of _Joining having DATE data type.

    If we try to insert data in DD/MM/YYYY format, then we get an error message:

    INSERT INTO Employee VALUES(1,'James','IT',3500,'25/05/2016');
    PostgreSQL DATE Format dd/mm/yyyy example
    PostgreSQL- Error Message DATE Format

    So now we will insert some data in this table using the PostgreSQL INSERT statement, and we will use the DD-Month-YYYY format to INSERT the Date_Of_Joining:

    INSERT INTO Employee VALUES(1,'James','IT',3500,'25-May-2016');
    INSERT INTO Employee VALUES(2,'Simona','Electrical',2500,'12-Aug-2018');
    INSERT INTO Employee VALUES(3,'Kiley','Mechanical',2250,'21-Oct-2019');
    INSERT INTO Employee VALUES(4,'Fletcher','IT',3000,'10-Jun-2017');
    INSERT INTO Employee VALUES(5,'Alisha','IT',2700,'16-Sep-2018');
    INSERT INTO Employee VALUES(6,'Chanel','Mechanical',2500,'07-Dec-2018');
    INSERT INTO Employee VALUES(7,'Erick','IT',3250,'13-Jul-2017');
    INSERT INTO Employee VALUES(8,'Amber','Electrical',2700,'05-Mar-2018');
    INSERT INTO Employee VALUES(9,'Stephen','Electrical',2000,'24-Nov-2020');
    INSERT INTO Employee VALUES(10,'Jose','HR',3700,'23-Jan-2016');
    PostgreSQL DATE Format dd/mm/yyyy
    PostgreSQL- Insert DATA DATE DMY Format

    We have inserted the DATE type values in DD-MON-YYYY format inside single quotation marks.

    We have successfully entered the data which can be checked by using the SELECT statement in PostgreSQL:

    SELECT *
    FROM Employee;
    DATE Format dd/mm/yyyy in PostgreSQL
    PostgreSQL DATA Inserted Successfully DATE Format

    It is clear from the screenshot that PostgreSQL stores the DATE type values in YYYY-MM-DD format irrespective of any format used while inserting the same, in this case, we used DD-MON-YYYY format to insert DATE type values and PostgreSQL stored it in YYYY-MM-DD format.

    In this section, we learned about PostgreSQL DATE Format DD/MM/YYYY or DD-MON-YYYY.

    Here is another simple example:

    In Postgresql, to show the date in a format like dd/mm/yyyy, here we will use the to_char function.

    Use the below code.

    SELECT to_char(now()::date,'dd/mm/yyyy') as currentdate;
    Postgresql date format dd/mm/yyyy
    Postgresql date format dd/mm/yyyy

    In the above output, we have formatted the date value specified format dd/mm/yyyy in the “to_char(now():: date,’ dd/mm/yyyy)” function, where the first datetime cast into date value using typecast:: date operator with the name of the data type to cast, then formatted in dd/mm/yyyy format.

    This is an example of PostgreSQL date format dd/mm/yyyy.

    Read Postgresql create user with password and PostgreSQL WHERE with examples

    PostgreSQL date format yyyy-mm

    In Postgresql, To format the date in yyyy-mm format only which means we will only show the year and month.

    Let’s run the below code to format the date in yyyy-mm.

    SELECT to_char(now()::date,'yyyy-mm') as year_month;
    Postgresql date format yyyy-mm
    Postgresql date format yyyy-mm

    This is an example of PostgreSQL date format yyyy-mm.

    PostgreSQL DATE Format dd/mm/yyyy hh mm

    In this section, we will learn about PostgreSQL DATE Format DD/MM/YYYY HH12:MI. PostgreSQL stores the DATE type values in YYYY-MM-DD format. So if we wish to INSERT DATE type values in DD/MM/YYYY HH MM format then we have to use TIMESTAMP data type. As it stores the preceding time as well.

    We will look at an example where we will insert in DD-MON-YYYY HH:MI format and will use the TO_CHAR() to produce the SELECT query output in DD/MM/YYYY HH12:MI format.

    First, connect to the database in PostgreSQL using the c command and the name of the database:

    c sqlserverguides

    Now create a table in PostgreSQL using these lines of code having a column with DATE data type:

    CREATE TABLE Employee(
    Emp_ID integer NOT NULL PRIMARY KEY,
    Name text NOT NULL,
    Dept text,
    Salary money,
    Date_Of_Joining TIMESTAMP);
    
    PostgreSQL DATE Format dd/mm/yyyy hh mm
    PostgreSQL Create Table TIMESTAMP

    Here we have created a column named Date_Of _Joining having TIMESTAMP data type.

    Now we will insert some data in this table using the PostgreSQL INSERT statement, and we will use the DD-MON-YYYY HH:MM format to INSERT the Date_Of_Joining:

    INSERT INTO Employee VALUES(1,'James','IT',3500,'25-May-2016 10:30');
    INSERT INTO Employee VALUES(2,'Simona','Electrical',2500,'12-Aug-2018 11:00');
    INSERT INTO Employee VALUES(3,'Kiley','Mechanical',2250,'21-Oct-2019 11:30');
    INSERT INTO Employee VALUES(4,'Fletcher','IT',3000,'10-Jun-2017 10:00');
    INSERT INTO Employee VALUES(5,'Alisha','IT',2700,'16-Sep-2018 09:30');
    INSERT INTO Employee VALUES(6,'Chanel','Mechanical',2500,'07-Dec-2018 10:15');
    INSERT INTO Employee VALUES(7,'Erick','IT',3250,'13-Jul-2017 10:45');
    INSERT INTO Employee VALUES(8,'Amber','Electrical',2700,'05-Mar-2018 11:15');
    INSERT INTO Employee VALUES(9,'Stephen','Electrical',2000,'24-Nov-2020 11:45');
    INSERT INTO Employee VALUES(10,'Jose','HR',3700,'23-Jan-2016 10:30');
    PostgreSQL DATE Format dd/mm/yyyy hh mm
    PostgreSQL- Insert DATA TIMESTAMP

    We have inserted the DATE type values in DD-MON-YYYY HH:MM format inside single quotation marks.

    We have successfully entered the data which can be checked by using the SELECT statement in PostgreSQL:

    SELECT *
    FROM Employee;
    DATE Format dd/mm/yyyy hh mm in PostgreSQL
    PostgreSQL- DATA Inserted Successfully TIMESTAMP

    Here we can see that the data has been inserted successfully and the Date_Of_Joining stores the TIMESTAMP in YYYY-MM-DD HH:MM:SS format.

    Now we will use the TO_CHAR() function in SELECT statement to get the TIMESTAMP in DD/MM/YYYY HH12:MI format:

    SELECT Emp_ID,Name,TO_CHAR(Date_Of_Joining, 'MM/DD/YYYY HH12:MI')
    FROM Employee;
    PostgreSQL SELECT Statement TIMESTAMP
    PostgreSQL- SELECT Statement TIMESTAMP

    We have specified the DD/MM/YYYY HH:MI format in the TO_CHAR() function inside the PostgreSQL SELECT statement.

    In this section, we learned about PostgreSQL DATE Format dd/mm/yyyy hh mm or DD/MM/YYYY HH12:MI.

    Another example:

    In Postgresql, To format date with time like dd/mm/yyyy hh mm where dd for a date, mm for a month, yyyy for a year, hh for an hour, mm for a month number.

    Use the below statement to show the date in dd/mm/yyyy hh mm.

    SELECT to_char(now(),'dd/mm/yyyy hh mm') as date_time;
    Postgresql date format dd/mm/yyyy hh mm
    Postgresql date format dd/mm/yyyy hh mm

    This is an example of PostgreSQL date format dd/mm/yyyy hh mm.

    Read PostgreSQL CASE with Examples

    PostgreSQL date format month name

    In Postgresql, We can show the date with the month name by providing the pattern name Month to the “to_char( )” function.

    Use the below syntax.

    SELECT to_char(now()::date, 'dd month yyyy') as date_time;
    Postgresql date format month name
    Postgresql date format month name

    This is an example of PostgreSQL date format month name.

    PostgreSQL DATE Format With Timezone

    In this section, we will learn about PostgreSQL DATE format With Timezone. PostgreSQL stores the DATE type values in YYYY-MM-DD format. So if we wish to INSERT DATE type values with Timezone then we have to use TIMESTAMPTZ data type, as it changes the timezone of the data using the SET command.

    So we will look at an example where we will switch between two timezones and note the difference.

    First, connect to the database in PostgreSQL using the c command and the name of the database:

    c sqlserverguides

    Now create a table in PostgreSQL using these lines of code having a column with DATE data type:

    CREATE TABLE Employee(
    Emp_ID integer NOT NULL PRIMARY KEY,
    Name text NOT NULL,
    Dept text,
    Salary money,
    Date_Of_Joining TIMESTAMPTZ);
    
    PostgreSQL Create Table TIMESTAMPTZ
    PostgreSQL- Create Table TIMESTAMPTZ

    Here we have created a column named Date_Of _Joining having TIMESTAMPTZ data type.

    Now we will insert some data in this table using the PostgreSQL INSERT statement, and we will use the DD-MON-YYYY HH:MM format to INSERT the Date_Of_Joining:

    INSERT INTO Employee VALUES(1,'James','IT',3500,'25-May-2016 13:30');
    INSERT INTO Employee VALUES(2,'Simona','Electrical',2500,'12-Aug-2018 14:00');
    INSERT INTO Employee VALUES(3,'Kiley','Mechanical',2250,'21-Oct-2019 14:30');
    INSERT INTO Employee VALUES(4,'Fletcher','IT',3000,'10-Jun-2017 13:00');
    INSERT INTO Employee VALUES(5,'Alisha','IT',2700,'16-Sep-2018 12:30');
    INSERT INTO Employee VALUES(6,'Chanel','Mechanical',2500,'07-Dec-2018 13:15');
    INSERT INTO Employee VALUES(7,'Erick','IT',3250,'13-Jul-2017 13:45');
    INSERT INTO Employee VALUES(8,'Amber','Electrical',2700,'05-Mar-2018 14:15');
    INSERT INTO Employee VALUES(9,'Stephen','Electrical',2000,'24-Nov-2020 14:45');
    INSERT INTO Employee VALUES(10,'Jose','HR',3700,'23-Jan-2016 13:30');
    PostgreSQL Insert Data TIMESTAMP 24 HOUR
    PostgreSQL- Insert Data TIMESTAMP 24 HOUR

    We have inserted the DATE type values in DD-MON-YYYY HH24:MM format inside single quotation marks.

    We have successfully entered the data which can be checked by using the SELECT statement in PostgreSQL:

    SELECT *
    FROM Employee;
    PostgreSQL DATE Format With Timezone
    PostgreSQL- DATA Inserted Successfully TIMESTAMPTZ

    Now we will set the TIMEZONE to ‘America/New_York’ using the SET command and note the difference:

    SET TIMEZONE = 'America/New_York';

    We can check the current TIMEZONE using the SHOW command:

    SHOW TIMEZONE;
    PostgreSQL SET TIMEZONE example
    PostgreSQL- SET TIMEZONE

    Now we will again use SELECT statement in PostgreSQL to look for the difference:

    SELECT Emp_ID,Name,Date_Of_Joining 
    From Employee;
    PostgreSQL TIMEZONE America
    PostgreSQL- TIMEZONE Set to America/New_York

    It is clear from the screenshot that the TIMEZONE for the TIMESTAMP type Date_Of_Joining has been changed to ‘America/New_York’ as there is a clear difference of 11 Hours in the Date_Of_Joining Field.

    In this section, we learned about PostgreSQL DATE Format With Timezone.

    Read PostgreSQL WHERE IN with examples

    PostgreSQL DATE Format 24 Hour

    In this section, we will learn about PostgreSQL DATE Format 24 Hour. PostgreSQL stores the DATE type values in YYYY-MM-DD format. So if we wish to INSERT DATE type values in 24HOUR format then we have to use TIMESTAMP data type. As it stores the preceding time as well.

    We will look at an example where we will insert in DD-MON-YYYY HH:MI format and will use the TO_CHAR() to produce the SELECT query output in DD/MM/YYYY HH24:MI format.

    First, connect to the database in PostgreSQL using the c command and the name of the database:

    c sqlserverguides

    Now create a table in PostgreSQL using these lines of code having a column with DATE data type:

    CREATE TABLE Employee(
    Emp_ID integer NOT NULL PRIMARY KEY,
    Name text NOT NULL,
    Dept text,
    Salary money,
    Date_Of_Joining TIMESTAMP);
    
    PostgreSQL DATE Format 24 Hour
    PostgreSQL Create Table TIMESTAMP

    Here we have created a column named Date_Of _Joining having TIMESTAMP data type.

    Now we will insert some data in this table using the PostgreSQL INSERT statement, and we will use the DD-MON-YYYY HH:MM format to INSERT the Date_Of_Joining:

    
    INSERT INTO Employee VALUES(1,'James','IT',3500,'25-May-2016 13:30');
    INSERT INTO Employee VALUES(2,'Simona','Electrical',2500,'12-Aug-2018 14:00');
    INSERT INTO Employee VALUES(3,'Kiley','Mechanical',2250,'21-Oct-2019 14:30');
    INSERT INTO Employee VALUES(4,'Fletcher','IT',3000,'10-Jun-2017 13:00');
    INSERT INTO Employee VALUES(5,'Alisha','IT',2700,'16-Sep-2018 12:30');
    INSERT INTO Employee VALUES(6,'Chanel','Mechanical',2500,'07-Dec-2018 13:15');
    INSERT INTO Employee VALUES(7,'Erick','IT',3250,'13-Jul-2017 13:45');
    INSERT INTO Employee VALUES(8,'Amber','Electrical',2700,'05-Mar-2018 14:15');
    INSERT INTO Employee VALUES(9,'Stephen','Electrical',2000,'24-Nov-2020 14:45');
    INSERT INTO Employee VALUES(10,'Jose','HR',3700,'23-Jan-2016 13:30');
    PostgreSQL DATE Format 24 Hour example
    PostgreSQL- Insert Data TIMESTAMP 24 HOUR

    We have inserted the DATE type values in DD-MON-YYYY HH24:MM format inside single quotation marks.

    We have successfully entered the data which can be checked by using the SELECT statement in PostgreSQL:

    SELECT *
    FROM Employee;
    DATE Format 24 Hour in PostgreSQL
    PostgreSQL- DATA Inserted Successfully TIMESTAMP 24HOUR

    Here we can see that the data has been inserted successfully and the Date_Of_Joining stores the TIMESTAMP in YYYY-MM-DD HH24:MM:SS format.

    Now we will use the TO_CHAR() function in SELECT statement to get the TIMESTAMP in DD/MM/YYYY HH12:MI format:

    SELECT Emp_ID,Name,TO_CHAR(Date_Of_Joining, 'MM/DD/YYYY HH24:MI')
    FROM Employee;
    PostgreSQL 24HOUR TIMESTAMP
    PostgreSQL- 24HOUR FORMAT TIMESTAMP

    We have specified the DD/MM/YYYY HH24:MI format in the TO_CHAR() function inside the PostgreSQL SELECT statement to display the TIMESTAMP in 24 HOUR Format.

    Another Example:

    In Postgresql, we can convert the string to date with a specific format, syntax is given below.

    to_date(string, format)

    string: It is a string that we will convert into a date.

    format: It is a pattern or format of a date.

    Let’s understand through different examples with different formats.

    SELECT to_date('20210325','yyyymmdd');
    Postgresql date format convert
    Postgresql date format convert
    SELECT to_date('20-feb-2019', 'dd-mon-yyyy');
    Postgresql date format convert
    Postgresql date format convert
    SELECT to_date('2021/06/21', 'yyyy/mm/dd');
    Postgresql date format convert
    Postgresql date format convert

    This is an example of PostgreSQL date format convert.

    You may also like the following PostgreSQL tutorials:

    • PostgreSQL DATE_PART() Function with examples
    • PostgreSQL TO_CHAR function
    • Create a stored procedure in PostgreSQL
    • PostgreSQL list databases
    • PostgreSQL Data Types

    In this tutorial, we learned, about PostgreSQL DATE Format. Also, we have covered these topics:

    • PostgreSQL DATE Format
    • PostgreSQL DATE Format INSERT
    • PostgreSQL DATE Format WHERE Clause
    • PostgreSQL DATE Format yyyymmdd
    • PostgreSQL DATE Format mm/dd/yyyy
    • PostgreSQL DATE Format dd/mm/yyyy
    • PostgreSQL date format yyyy-mm
    • PostgreSQL date format month name
    • PostgreSQL DATE Format dd/mm/yyyy hh mm
    • PostgreSQL DATE Format With Timezone
    • PostgreSQL DATE Format 24 Hour

    Bijay

    I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

    Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

    Понравилась статья? Поделить с друзьями:
  • Postgresql как изменить расположение базы данных
  • Postgresql как изменить порт подключения
  • Powershell error view
  • Powershell error variable
  • Powershell error handling