【问题标题】:Import date dd/mm from txt to table with SQL使用 SQL 将日期 dd/mm 从 txt 导入表
【发布时间】:2016-07-13 23:28:33
【问题描述】:

我是一个初学者,已经到处搜索了,所以请多多包涵。

我有一个包含此类数据 (DD/MM) 的 txt 文件,并且;作为分隔符:

01/10;10/06;15/11;10/07
01/10;10/06;15/11;10/07
01/11;20/06;10/11;30/07
01/11;20/06;10/11;30/07
10/11;20/06;20/01;30/07
01/10;01/06;15/11;30/06

首先,我set datestyle to European;

所以我有 DateStyle - "ISO, DMY"。

之后,我尝试使用 postgresql 将这些数据导入到 pheno 表的某些列中(参见下面的代码):

COPY pheno(planting_onset, harvesting_onset, planting_end, harvesting_end) 
FROM '/home/user/Documents/worldcrops/algeria_times.txt' DELIMITERS ';';

并给出以下错误:

ERROR:  invalid input syntax for type date: "01/10"
CONTEXT:  COPY pheno, line 1, column planting_onset: "01/10"
********** Error **********

ERROR: invalid input syntax for type date: "01/10"
SQL state: 22007
Context: COPY pheno, line 1, column planting_onset: "01/10"

问题:如何将此数据类型 DD/MM 复制到表中,其中列的日期为“数据类型”?我应该更改“数据类型”列吗?

提前致谢。

【问题讨论】:

  • 文本文件中的数据都不是日期。日期由月、日和年组成。你只有三分之二。 DMY 表示Day、Month、Year,同样你只有三分之二。你不能有一个 Date 类型而没有一个 Date 放入它。 (如果你仔细想想,这确实是一个常识问题。)
  • 您的 CSV 文件中似乎有一些额外的空白字符。您是否有机会删除它们?
  • 同意,肯·怀特。那么我应该将列的“日期类型”更改为 char 吗?如果我想计算一年内 2 个日期之间的差异(请注意,这些日期属于任何不特定的年份),该怎么办?

标签: sql postgresql date


【解决方案1】:

它期待 DMY,但你只给它几天和几个月。这有点骇人听闻,但我认为它应该可以工作:

ALTER TABLE pheno 
ADD planting_onset_temp VARCHAR(16), 
    harvesting_onset_temp VARCHAR(16),  
    planting_end_temp VARCHAR(16), 
    harvesting_end_temp VARCHAR(16);
COPY pheno(planting_onset_temp, harvesting_onset_temp, planting_end_temp, harvesting_end_temp) FROM '/home/user/Documents/worldcrops/algeria_times.txt' DELIMITERS ';';
UPDATE pheno 
SET planting_onset   = CONCAT(planting_onset_temp, '/2016'), 
    harvesting_onset = CONCAT(harvesting_onset_temp, '/2016'), 
    planting_end     = CONCAT(planting_end_temp, '/2016'),
    harvesting_end   = CONCAT(harvesting_end_temp, '/2016');
ALTER TABLE pheno DROP COLUMN planting_onset_temp, harvesting_onset_temp, planting_end_temp, harvesting_end_temp;

将“/2016”替换为任何相关的年份。

【讨论】:

  • 谢谢@Caius。尽管我没有使用您的代码来解决问题,但您向我展示了另一种可能的方式,我可以在类似情况下使用。我将格式更改为 YYYY-MM-DD 因为它不接受 DD-MM-YYYY 由于 DD 中的第一个 0(例如:01/10/2016),现在它可以复制到带有日期的列类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 2020-06-22
  • 2014-05-30
相关资源
最近更新 更多