Postgresql 寻找将日期格式DMY的位置交换为YMD的解决方案

Postgresql 寻找将日期格式DMY的位置交换为YMD的解决方案,postgresql,Postgresql,我的数据库有些问题。 我上传了多个excel文件中的数据,每个文件都有特定的日期格式。某个时间段DD/MM/YYYY和某个时间段YYYY/MM/DD该列为字符变量。 我想让它们成为YYYY/MM/DD。一个简单的解决方案: select regexp_replace('05/01/2019', '(\d\d)/(\d\d)/(\d\d\d\d)', '\3/\2/\1') regexp_replace ---------------- 2019/01/05 (1 row) 您可以使用

我的数据库有些问题。 我上传了多个excel文件中的数据,每个文件都有特定的日期格式。某个时间段DD/MM/YYYY和某个时间段YYYY/MM/DD该列为字符变量。 我想让它们成为YYYY/MM/DD。

一个简单的解决方案:

select regexp_replace('05/01/2019', '(\d\d)/(\d\d)/(\d\d\d\d)', '\3/\2/\1')

 regexp_replace 
----------------
 2019/01/05
(1 row)
您可以使用

update my_table
set date_column = regexp_replace(date_column, '(\d\d)/(\d\d)/(\d\d\d\d)', '\3/\2/\1')
但是,基本上应该将日期存储在date类型的列中。使用该功能将不同格式的文本转换为日期:

create or replace function iso_date(text)
returns date language sql immutable as $$
    select case
        when $1 like '__/__/____' then to_date($1, 'DD/MM/YYYY')
        when $1 like '____/__/__' then to_date($1, 'YYYY/MM/DD')
    end
$$
上面是一个例子,如果您有更多不同的格式,您可以修改该函数。现在可以通过以下方式更改列类型:

alter table my_table alter date_column type date using iso_date(date_column);

阅读文档中有关和的更多信息。

非常感谢,这非常有帮助。如果这有帮助,我很高兴。考虑接受答案,以表明问题已经解决。