Sub topic 8
to_char, to_number, to_date and to_timestamp
This chapter assumes you know the plain cast syntaxes (CAST, ::) and the basic types numeric, text, date and timestamptz. You also need a psql session.
A plain cast uses the type's own input function, which only understands the standard layout. '27/11/2026'::date depends on the DateStyle setting, and '1,234.50'::numeric always fails. The four formatting functions take a template that describes the layout, so you can convert in both directions.
The four functions
| Function | Converts | Returns |
|---|---|---|
| `to_char(value, template)` | number, date, timestamp or interval to text | `text` |
| `to_number(text, template)` | text to a number | `numeric` |
| `to_date(text, template)` | text to a date | `date` |
| `to_timestamp(text, template)` | text to a timestamp | `timestamptz` |
to_timestamp also has a one-argument form, to_timestamp(double precision), which converts Unix epoch seconds. It is not a formatting function and takes no template.
SELECT to_char(1234.5, 'FM999,999.00') AS formatted,
to_number('1,234.50', '9,999.99') AS parsed_number,
to_date('27/11/2026', 'DD/MM/YYYY') AS parsed_date;This returns 1,234.50, the numeric 1234.50 and the date 2026-11-27.
Number templates
Each template character stands for one position in the number.
| Pattern | Meaning |
|---|---|
| `9` | A digit position. A leading or trailing zero in that position may be dropped. |
| `0` | A digit position that always prints a digit. |
| `,` | A group separator, printed literally. |
| `.` | A decimal point, printed literally. |
| `G` and `D` | The locale's group separator and decimal point. |
| `FM` | Fill mode. Removes padding blanks from the output. |
| `S`, `MI`, `PR` | Sign handling: a sign, a trailing minus, or angle brackets for negatives. |
The difference between 9 and 0 shows up with values below 1:
SELECT to_char(0.5, 'FM990.00') AS with_zero,
to_char(0.5, 'FM999.00') AS with_nine,
to_char(1234.5, '999,999.00') AS padded;The results are 0.50, .50 and 1,234.50. The last one keeps a leading blank, which is the position reserved for a sign. FM removes that blank, so use it whenever the result goes into a report or a file.
If the value does not fit the template, to_char fills the field with # characters instead of raising an error. to_char(12345, '999') returns a string of hashes. Give the template at least as many digit positions as your largest value needs.
to_number is stricter in one way and looser in another. It returns numeric, so you can cast the result to another type. It also skips template characters it does not need to match, which means separators are not validated:
SELECT to_number('1,234.50', '9,999.99') AS ok,
to_number('12-34', '99,99') AS lenient;The second call returns 1234. The comma in the template consumes one input character, whatever it is. Do not rely on to_number to reject malformed input.
Currency symbols are a common problem. The L pattern prints or reads the locale's currency symbol, so it depends on lc_monetary. A portable alternative is to strip unwanted characters first and then cast:
SELECT regexp_replace('$1,234.50', '[^0-9.]', '', 'g')::numeric AS amount;Date and time templates
| Pattern | Meaning |
|---|---|
| `YYYY`, `YY` | Year with four or two digits |
| `MM`, `Mon`, `Month` | Month as a number, an abbreviated name, or a full name |
| `DD` | Day of month |
| `Dy`, `Day` | Abbreviated or full weekday name |
| `HH24`, `HH12` | Hour on a 24-hour or 12-hour clock |
| `MI`, `SS` | Minutes and seconds |
| `AM` or `PM` | Meridian indicator for use with `HH12` |
| `TH` | Ordinal suffix (`1st`, `2nd`) in `to_char` |
A quoted string such as "at" is literal text. Month and day names follow the lc_time setting. Month is padded to nine characters unless you add FM.
SELECT to_char(timestamp '2026-11-27 21:43:07', 'YYYY-MM-DD HH24:MI:SS') AS iso_like,
to_char(date '2026-11-27', 'FMDay, DD Mon YYYY') AS readable;The results are 2026-11-27 21:43:07 and Friday, 27 Nov 2026 in an English locale.
Parsing dates and timestamps
to_date and to_timestamp read the input from left to right against the template. They are forgiving about separators. Any non-alphanumeric character in the template skips one input character, whatever that character is, and extra blanks in the input are ignored:
SELECT to_date('2026/11/27', 'YYYY-MM-DD') AS slash_ok,
to_date('27 Nov 2026', 'DD Mon YYYY') AS named_month;Both calls return 2026-11-27. They are not forgiving about impossible dates. to_date('2026-02-30', 'YYYY-MM-DD') raises date/time field value out of range in current versions.
Template fields that you leave out take defaults. A missing year, month or day falls back to a default instead of the current date, so always include every field you need.
Time zones
to_timestamp(text, text) returns timestamptz. If the input has no zone, the server reads it as local time in the session TimeZone. The result is therefore an instant that depends on the session:
SET TIME ZONE 'UTC';
SELECT to_timestamp('27/11/2026 21:43', 'DD/MM/YYYY HH24:MI') AS utc_session;
SET TIME ZONE 'America/New_York';
SELECT to_timestamp('27/11/2026 21:43', 'DD/MM/YYYY HH24:MI') AS ny_session;The first call gives 2026-11-27 21:43:00+00 and the second gives 2026-11-27 21:43:00-05. These are different instants. If the text is in a known zone that differs from the session zone, convert in two steps. First drop to a plain timestamp, which keeps the parsed wall-clock value. Then attach the zone you know:
SELECT to_timestamp('27/11/2026 21:43', 'DD/MM/YYYY HH24:MI')::timestamp
AT TIME ZONE 'Europe/Paris' AS paris_instant;to_char has the matching behavior in the other direction. A timestamptz is formatted in the session time zone, so two sessions can print different text for the same stored value. To print a fixed zone, apply AT TIME ZONE first.
The one-argument form converts epoch seconds. In a UTC session, to_timestamp(0) returns 1970-01-01 00:00:00+00. To go back to epoch seconds, use extract(epoch FROM ts).
Common errors
- Wrong template for the input.
to_date('13/11/2026', 'MM/DD/YYYY')fails with a field-out-of-range error. Check month and day order first. - Using
to_numberas a validator. It accepts input that looks wrong, as shown above. Validate with a regular expression if you need strict checking. - Expecting
pg_input_is_validto check a template. That function tests a type's input function, such asinteger. It cannot test ato_datetemplate. To test a layout, check the text with a regular expression in aCASEexpression before you call the parser. - Locale surprises.
Month,Day,G,DandLchange withlc_time,lc_numericandlc_monetary. Code that works on your machine can print different text on a server with another locale. - Padding and blanks. Without
FM,to_charpads numbers and names. Comparing the output with a literal string then fails on the extra spaces.
Exercise
A feed contains the text '03/04/2026 07:15 PM'. It is day/month/year in the UTC+0 zone. Write one expression that returns it as a timestamptz instant, whatever the session TimeZone is, and say which template patterns you used.
Show answer
SELECT totimestamp('03/04/2026 07:15 PM', 'DD/MM/YYYY HH12:MI PM')::timestamp AT TIME ZONE 'UTC'; The template uses DD, MM and YYYY for the date, HH12 for the 12-hour clock, MI for minutes and PM for the meridian. totimestamp reads the text in the session zone, the cast to timestamp keeps the wall-clock value, and AT TIME ZONE 'UTC' marks that value as UTC, so the result is 2026-04-03 19:15:00+00 in a UTC session and the same instant in any other session.