Sub topic 11
Formatting and Parsing Text
This chapter covers converting between timestamps and text with to_char, to_timestamp, to_date, and extract. It assumes you know the difference between timestamp and timestamptz, that the session TimeZone setting controls how timestamptz is displayed, and that AT TIME ZONE converts between the two types.
Two ways to turn text into a timestamp
PostgreSQL gives you two routes from text to a temporal value:
- Casting (
'2024-06-01T09:00:00Z'::timestamptz) uses the general input parser. It accepts ISO 8601 and many other styles. For ambiguous styles such as01/06/2024, theDateStylesetting decides whether that means 1 June or 6 January. - Template functions (
to_timestamp,to_date) take a format string that you write yourself. They ignoreDateStyle, so the same input and template give the same result in every session.
Use a cast for ISO 8601 input. Use to_timestamp or to_date when the text follows a fixed non-ISO layout, such as 01/06/2024 09:30 from a spreadsheet export.
Formatting with to_char
to_char(value, template) returns text. The template is a string of pattern codes mixed with literal characters. The value can be a date, timestamp, timestamptz, interval, or a number.
For a timestamptz, to_char first converts the value to the session TimeZone, then formats the local fields:
SET TimeZone = 'America/New_York';
SELECT to_char(TIMESTAMPTZ '2024-06-01 07:00:00+00',
'YYYY-MM-DD HH24:MI:SS TZ');
-- 2024-06-01 03:00:00 EDT
SELECT to_char(TIMESTAMPTZ '2024-06-01 07:00:00+00',
'FMDay, FMDD FMMonth YYYY, HH12:MI AM');
-- Saturday, 1 June 2024, 03:00 AMThe same instant formatted in another session zone gives different text. The output is only text, so it no longer carries any zone information unless the template includes one.
Common pattern codes
| Pattern | Meaning | Example output |
|---|---|---|
| `YYYY` | Four-digit year | `2024` |
| `MM` | Month number (01 to 12) | `06` |
| `DD` | Day of month (01 to 31) | `01` |
| `HH24` | Hour, 00 to 23 | `15` |
| `HH12` or `HH` | Hour, 01 to 12 | `03` |
| `MI` | Minute | `30` |
| `SS` | Second | `05` |
| `MS`, `US` | Milliseconds, microseconds | `250`, `250000` |
| `AM` | Meridian indicator | `PM` |
| `Mon`, `Month` | Month name | `Jun`, `June` |
| `Dy`, `Day` | Day name | `Sat`, `Saturday` |
| `IYYY`, `IW`, `ID` | ISO 8601 year, week, weekday | `2024`, `22`, `6` |
| `TZ` | Zone abbreviation (output only) | `EDT` |
| `TZH:TZM` | Offset hours and minutes | `-04:00` |
| `OF` | Offset, short form | `-04` |
Formatting gotchas
MMis month andMIis minute. The template'HH:MM'prints the hour followed by the month. This is the most common mistake withto_char.HHis a 12-hour clock. WithoutAMin the template, 3 PM and 3 AM print identically. UseHH24unless you also print the meridian.- Names are padded.
Monthpads to nine characters andDaypads to nine as well. TheFM(fill mode) prefix suppresses padding and leading zeros, soFMDDgives1instead of01. - Literal text needs double quotes. Letters in the template can be read as patterns. To print the
Tin an ISO-style string, write'YYYY-MM-DD"T"HH24:MI:SS'. - Names are English by default. Add the
TMprefix (TMDay,TMMonth) to use the language of thelc_timesetting.
Parsing with to_timestamp and to_date
to_timestamp(text, template) returns a timestamptz. If the text has no offset, PostgreSQL interprets the fields in the session TimeZone. If the text has an offset, parse it with TZH (and TZM if minutes are present).
SET TimeZone = 'UTC';
-- No offset in the text: read as UTC because that is the session zone
SELECT to_timestamp('01/06/2024 09:30', 'DD/MM/YYYY HH24:MI');
-- 2024-06-01 09:30:00+00
-- Offset in the text: the offset wins
SELECT to_timestamp('2024-06-01 09:30 +02', 'YYYY-MM-DD HH24:MI TZH');
-- 2024-06-01 07:30:00+00
SELECT to_date('1 Jun 2024', 'DD Mon YYYY');
-- 2024-06-01The first call would return a different instant in a session set to Europe/Paris, because the same wall-clock text maps to a different UTC instant. If your text carries no zone, set TimeZone explicitly before parsing. Otherwise use to_timestamp(...) on a plain timestamp conversion with AT TIME ZONE, which makes the zone part of the query:
SELECT to_timestamp('01/06/2024 09:30', 'DD/MM/YYYY HH24:MI')::timestamp
AT TIME ZONE 'Europe/Paris';This is clearer, but only if the session zone is known to you. If you cannot trust it, cast the result of to_timestamp carefully or parse into a timestamp first. For example, cast the ISO form '2024-06-01 09:30'::timestamp AT TIME ZONE 'Europe/Paris', which does not depend on the session zone at all.
to_date returns a date and ignores any time fields in the text.
Epoch values
to_timestamp(double precision) takes seconds since 1970-01-01 00:00:00 UTC and returns a timestamptz. It is the inverse of extract(epoch FROM ...):
SET TimeZone = 'UTC';
SELECT to_timestamp(1704067200);
-- 2024-01-01 00:00:00+00
SELECT extract(epoch FROM TIMESTAMPTZ '2024-01-01 00:00:00+00');
-- 1704067200Parsing gotchas
- Parsing is lenient about spacing. Extra whitespace in the input is skipped, and non-pattern characters in the template match any single character. Add the
FX(fixed format) prefix, as in'FXYYYY-MM-DD', to require exact widths and separators. - Impossible dates raise an error. A value such as
2024-02-30fails with a "date/time field value out of range" error. A query that parses a whole column stops at the first bad row. - Missing fields get defaults. Fields you do not supply default to the start of year 1 (January 1, 00:00:00). Parsing only
'HH24:MI'does not give today's date. TZis output only. Abbreviations likeEDTcan be printed but not parsed. Parse numeric offsets withTZHandTZM.- Short years are guessed. Two-digit years such as
YYare mapped to the year nearest 2020, so useYYYYwhenever the data has four digits.
PostgreSQL 16 added pg_input_is_valid, which tests text against a type without raising an error. It works with the casting route:
SELECT pg_input_is_valid('2024-02-30', 'date');
-- falseOn earlier versions, validate in the application or in a PL/pgSQL function with an exception handler.
Extracting numeric fields
When you need a number rather than text, extract(field FROM value) is cleaner than parsing the output of to_char. Since PostgreSQL 14 it returns numeric; earlier versions return double precision.
| Field | Meaning |
|---|---|
| `year`, `month`, `day` | Calendar fields in the session zone for `timestamptz` |
| `hour`, `minute`, `second` | Time fields; `second` includes fractions |
| `dow` | Day of week, 0 (Sunday) to 6 |
| `isodow` | ISO day of week, 1 (Monday) to 7 |
| `week` | ISO 8601 week number |
| `epoch` | Seconds since 1970-01-01 00:00:00 UTC |
Two behaviors to remember:
- On a
timestamptz, calendar fields come from the session zone. At2024-06-01 23:30:00-04,extract(day ...)is 1 inAmerica/New_Yorkand 2 inUTC. - On a plain
timestamp,extract(epoch ...)treats the value as if it were UTC, since there is no zone to apply. The result is a nominal number, not a true instant.
A safe round trip
When text must be stored or sent and read back later, include the offset so the value does not depend on either session's setting:
SET TimeZone = 'America/New_York';
SELECT to_char(TIMESTAMPTZ '2024-06-01 07:00:00+00',
'YYYY-MM-DD"T"HH24:MI:SSTZH:TZM');
-- 2024-06-01T03:00:00-04:00A reader in any zone can parse this text back to the same instant, using a cast or to_timestamp with TZH:TZM.
Exercise
A session runs SET TimeZone = 'Asia/Tokyo';. What does SELECT to_char(TIMESTAMPTZ '2024-06-01 07:00:00+00', 'YYYY-MM-DD HH24:MI'); return, and why?
Show answer
It returns 2024-06-01 16:00. to_char converts a timestamptz to the session TimeZone before formatting, and Tokyo is UTC+9, so 07:00 UTC becomes 16:00 local time.
Exercise
A report uses to_char(created_at, 'YYYY-MM-DD HH:MM') and shows 2024-06-01 03:06 for an event at 15:30 on June 1. Name both bugs and write the corrected template.
Show answer
HH is the 12-hour clock, so 15 prints as 03. MM is the month, so the minutes print as 06 instead of 30. The corrected template is 'YYYY-MM-DD HH24:MI'.
Exercise
Why can to_timestamp('2024-06-01 09:30', 'YYYY-MM-DD HH24:MI') return different instants for two users, and how do you make the result independent of the session?
Show answer
The text has no offset, so the fields are read in each session's TimeZone. Either include an offset in the text and parse it with TZH, or parse into a plain timestamp and name the zone, for example '2024-06-01 09:30'::timestamp AT TIME ZONE 'Europe/Paris'.