I'm trying to validate strings to timestamps from several CSVs and simply casting them to timestamptz will fail due to the impossibility of forcing an unique datetime format:
select '10/31/2010'::timestamp --fail due to "different datestyle"
select '31/10/2010'::timestamp --works
I thought to_timestamp() would do the trick, but something like:
select to_timestamp('31/02/2014 14:30', 'DD/MM/YYYY HH24:MI');
will return "2014-03-03 14:30:00-05" instead of throwing an exception
So I thought of using this approach, that reverts back the output to text using to_char and comparing it with the original input, but a mask like 'DD/MM/YYYY HH24:MI' will cast "06/03/2014 0:06" to "06/03/2014 00:06", the strings are different!
CREATE OR REPLACE FUNCTION to_timestamp_safe(IN p_date text, IN p_format text, OUT r_date timestamp without time zone)
RETURNS timestamp without time zone AS
$BODY$
BEGIN
r_date = TO_TIMESTAMP(p_date, p_format);
IF TO_CHAR(r_date, p_format) != p_date THEN
RAISE EXCEPTION 'Input date % does not match output date %', p_date, r_date;
END IF;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
The following example fails where it should work:
select to_timestamp_safe ('06/03/2014 0:06', 'DD/MM/YYYY HH24:MI');
output:
ERROR: Input date 06/03/2014 0:06 does not match output date 2014-03-06 00:06:00
SQL state: P0001
Is there a smart way of safely validate strings to timestamptz without the above pitfalls?
to_timestamp
that doesn't normalize dates with days out of range, with a boolean flag for that. (It's long annoyed me that Pg fixes, rather than rejects, such dates). I don't see any easy way to do what you're describing as things stand.FM
modifier, your given example would work:SELECT to_timestamp_safe ('06/03/2014 0:06', 'DD/MM/YYYY FMHH24:MI');
But that's far from a general solution, which I don't see either.