Mac OSX Shell脚本解析ISO 8601日期并添加一秒?

问题描述:

我想弄清楚如何使用ISO 8601格式的时间戳解析文件,添加一秒钟然后将它们输出到文件。Mac OSX Shell脚本解析ISO 8601日期并添加一秒?

我发现的所有例子并没有真正告诉我如何用ISO 8601日期/时间字符串来做到这一点。

举例: 读的像次CSV: “2017-02-15T18:47:59”(有些是正确的,有些则没有)

,并在新文件中吐出“2017-02- “15T18:48:00”

主要是为了纠正一堆日期有59秒的结束时间,以达到1秒的标记。

这是我目前的进度:

#!/bin/bash 
while IFS='' read -r line || [[ -n "$line" ]]; do 
    # startd=$(date -j -f '%Y%m%d' "$line" +'%Y%m%d'); 
    # echo "$startd"; 
    startd=$(date -j -u -f "%a %b %d %T %Z %Y" $line) 
    #startd=$(date -j -f '%Y%m%d' "$line" +'%Y%m%d'); 
    echo "$startd"; 

done < "$1" 

任何帮助,将不胜感激

这可能做的工作

perl -MTime::Piece -nlE '$f=q{%Y-%m-%dT%H:%M:%S};$t=Time::Piece->strptime($_,$f)+1;say $t->strftime($f)' < dates.txt 

如果dates.txt包含

2017-02-15T18:47:59 
2016-02-29T23:59:59 
2017-02-28T23:59:59 
2015-12-31T23:59:59 
2010-10-10T10:10:10 

以上产生

2017-02-15T18:48:00 
2016-03-01T00:00:00 
2017-03-01T00:00:00 
2016-01-01T00:00:00 
2010-10-10T10:10:11 

jm666's helpful perl answer将比你的基于shell循环的方法快得多。

这就是说,如果你想在MacOS你bash代码的工作,其BSDdate实现,这里有一个解决方案:

# Define the input date format, which is also used for output. 
fmt='%Y-%m-%dT%H:%M:%S' 

# Note: -j in all date calls below is needed to suppress setting the 
#  system date. 
while IFS= read -r line || [[ -n "$line" ]]; do 

    # Parse the line at hand using input format specifier (-f) $fmt, 
    # and output-format specifier (+) '%s', which outputs a Unix epoch 
    # timestamp (in seconds). 
    ts=$(date -j -f "$fmt" "$line" +%s) 

    # See if the seconds-component (%S) is 59... 
    if [[ $(date -j -f %s "$ts" +%S) == '59' ]]; then 
     # ... and, if so, add 1 second (-v +1S). 
     line=$(date -j -f %s -v +1S "$ts" +"$fmt") 
    fi 

    # Output the possibly adjusted timestamp. 
    echo "$line" 

done < "$1" 

注意,输入的日期,如2017-02-15T18:47:59被解释为地方时间,因为它们不包含时区信息。