to_timestamp Parses Fixed Format Input
to_timestamp(text, format) is the inverse of to_char: quoted literals, ignored trailing input, missing fields filled with minimum values, mismatch raises.
Code
-- to_timestamp(text, format):按显式格式解析字符串,是 to_char 的逆操作
SELECT to_timestamp('21/06/2026 14:30', 'DD/MM/YYYY HH24:MI') AS parsed;
-- 字面字符用双引号包裹;末尾多余输入被忽略
SELECT to_timestamp('2026-06-21 08:00 UTC', 'YYYY-MM-DD HH24:MI') AS parsed_loose;
-- 缺省字段补齐规则:省略的部分取最小值(月 1 日、0 点)
SELECT to_timestamp('2026', 'YYYY') AS year_only;
-- 常见用法:把日志里的文本时间列转成 timestamptz 再排序
CREATE TABLE raw_logs (id int, logged text);
INSERT INTO raw_logs VALUES
(1, '2026-06-21 08:00'),
(2, '2026-06-21 07:30');
SELECT id, to_timestamp(logged, 'YYYY-MM-DD HH24:MI') AS logged_at
FROM raw_logs
ORDER BY logged_at; -- 07:30 排在前,按真实时间而非字符串排序The shape of the program
What runs here is SELECT / INSERT / CREATE — raw_logs are the objects involved.
In terms of clauses, the statements use: an ORDER BY that fixes the output order.
Applying it
Run the statement against the raw_logs table.
Statements that matter
SELECT id, to_timestamp(logged, 'YYYY-MM-DD HH24:MI') AS logged_at
FROM raw_logs
ORDER BY logged_at; -- 07:30 排在前,按真实时间而非字符串排序
INSERT INTO raw_logs VALUES
(1, '2026-06-21 08:00'),
(2, '2026-06-21 07:30');
SELECT to_timestamp('2026-06-21 08:00 UTC', 'YYYY-MM-DD HH24:MI') AS parsed_loose;
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- The references are `raw_logs`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.