Cast varchar type to date
13,416
When you cast text
or varchar
to date
, the default date format of your installation is expected - depending on the datestyle
setting in your postgresql.conf
.
Generally, colon (:
) is a time separator, In a simple cast, PostgreSQL will probably try to interpret '2011:06:15' as time - and fail.
To remove ambiguity use to_date()
with a matching pattern for your dates:
ALTER TABLE table_name
ALTER COLUMN date_time type date
USING to_date(date_time, 'YYYY:MM:DD'); -- pattern for your example
Related videos on Youtube
Author by
Lo Bizzarri
Updated on July 11, 2022Comments
-
Lo Bizzarri almost 2 years
I'd like to change a specific column in my PostgreSQL database from
character_varying
type to typedate
. Date is in the formatyyyy:mm:dd
I tried to do:
alter table table_name alter column date_time type date using (date_time::text::date);
But I received an error message:
date/time field value out of range: "2011:06:15"
-
Lo Bizzarri over 11 yearsThanks a lot, it works! But now I have the same problem with the hour column. It's a string and I'd like to trasform it in time type, but I don't know how to do it. Can you help me even with this problem? Thanks in advance.
-
Erwin Brandstetter over 11 years@LoBizzarri: Piece of cake with
to_timestamp()
. Did you follow the link I provided? If it's still giving you static, post another question with example of what you have and what you want. -
Lo Bizzarri over 11 yearsSorry, yesterday I had made a mistake in the command line. Now it is ok, thanks! I used: ALTER TABLE table_name ALTER COLUMN hour_time type time USING to_timestamp(hour_time, 'HH24:MI:SS');