dateawkdate-formattingweek-numberdate-manipulation

Using awk, how to convert dates to week and quarter?


Using awk, how to convert dates (yyyy-mm-dd) to week and quarter (first day of week set to monday)?

Input:

a;2016-04-25;10
b;2016-07-25;20
c;2016-10-25;30
d;2017-02-25;40

Wanted output:

a;2016-04-25;10;2016-w17;2016-q2
b;2016-07-25;20;2016-w30;2016-q3
c;2016-10-25;30;2016-w43;2016-q4
d;2017-02-25;40;2017-w8;2017-q1

Solution

  • awk solution:

    awk -F';' '{ split($2,d,"-"); w = strftime("%W", mktime(d[1]" "d[2]" "d[3]" 00 00 00")); 
               q = int((d[2]+2)/3); 
               print $0,d[1]"-w"w,d[1]"-q"q}' OFS=';' file
    

    The output:

    a;2016-04-25;10;2016-w17;2016-q2
    b;2016-07-25;20;2016-w30;2016-q3
    c;2016-10-25;30;2016-w43;2016-q4
    d;2017-02-25;40;2017-w08;2017-q1
    

    https://www.gnu.org/software/gawk/manual/html_node/Time-Functions.html