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.

SqlData Fetching

Code

snippet
-- 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

FAQ

Which tables appear in this script?
The references are `raw_logs`.