将varchar类型转换为日期 [英] Cast varchar type to date
问题描述
我想将PostgreSQL数据库中的一个特定列从 character_varying
类型更改为键入 date
。日期格式为 yyyy:mm:dd
I'd like to change a specific column in my PostgreSQL database from character_varying
type to type date
. Date is in the format yyyy:mm:dd
我试图这样做:
alter table table_name
alter column date_time type date using (date_time::text::date);
但是我收到一条错误消息:
But I received an error message:
日期/时间字段值超出范围:2011:06:15
date/time field value out of range: "2011:06:15"
推荐答案
当您将文本
或 varchar
转换为 date
,预期安装的默认日期格式取决于设置在 postgresql.conf
中。
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
.
通常,冒号(:
)是一个时间分隔符,在一个简单的转换中,PostgreSQL可能会尝试解释2011: 06:15'作为时间 - 并且失败。
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
这篇关于将varchar类型转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!