1

我有一个日期时间格式如下的 CSV 文件:

8/2/2012 1:34:01 PM

我需要找到此类日期的所有出现(可能是正则表达式)并将其(在文件中)转换为 mysql 默认日期时间格式(2012-08-02 13:34:01)。

我找到

date --date="8/2/2012 1:34:01 PM" +"%F %T"

工作正常,我得到了正确的结果。解决方案是找到所有出现格式错误的日期并将其传递给上述日期函数。

CSV 文件中的单行如下所示:

"Data 1","Data 2","Data 3","Data 4","100000000100","100000002263","10/31/2012 10:02:03 AM","1/29/1999 1:54:50 PM","11/6/2012 8:47:01 PM","S"

非常感谢!

4

3 回答 3

2

你可以吗?

awk -F, -vOFS=','  '{for (i=7;i<=9;i++) {"date --date="$i" +\"%F %T\"" |getline $i;$i="\""$i"\""}}1' file

用那一行测试:

kent$  echo '"Data 1","Data 2","Data 3","Data 4","100000000100","100000002263","10/31/2012 10:02:03 AM","1/29/1999 1:54:50 PM","11/6/2012 8:47:01 PM","S"'|awk -F, -vOFS=','  '{for (i=7;i<=9;i++) {"date --date="$i" +\"%F %T\"" |getline $i;$i="\""$i"\""}}1'
"Data 1","Data 2","Data 3","Data 4","100000000100","100000002263","2012-10-31 10:02:03","1999-01-29 13:54:50","2012-11-06 20:47:01","S"
于 2013-01-15T11:20:00.593 回答
0

我会使用带有适当 CSV 解析器的工具。这是一个红宝石示例

ruby -e '
  require "csv"
  require "date"

  def format_date(date)
    DateTime.strptime(date, "%m/%d/%Y %r").strftime "%Y-%m-%d %T"
  end

  CSV.foreach ARGV[0] do |row|
    [6,7,8].each {|i| row[i] = format_date row[i]}
    puts CSV.generate_line row, {:force_quotes => true}
  end
' file.csv

给定您的样本输入,此输出

"Data 1","Data 2","Data 3","Data 4","100000000100","100000002263","2012-10-31 10:02:03","1999-01-29 13:54:50","2012-11-06 20:47:01","S"
于 2013-01-15T14:34:24.877 回答
0

如果使用 perl 是一个选项,这应该符合您的要求

#! /usr/bin/perl

use strict;
use warnings;

while (my($m, $d, $y, $H, $M, $S, $a) = m!\"(\d+)/(\d+)/(\d+)\s+(\d+):(\d+):(\d+)\s+([ap]m)\"!i) {
    $H += 12 if ($a =~ m/pm/i);
    my $dt = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $y, $m, $d, $H, $M, $S);
    s!!$dt!;
}

调用它

perl -i.bak -p convert.pl csv.txt

这会将日期转换为 MySQL 格式。它还会创建一个备份文件csv.txt.bak

于 2013-01-15T12:20:03.807 回答