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

对着背影说爱祢 提交于 2019-12-08 13:48:11

问题


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

回答1:


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

  • split($2,d,"-") - split the 2nd field (date) by separator -

  • mktime(datespec) - turn datespec (date specification) into a timestamp

  • strftime("%W", mktime(d[1]" "d[2]" "d[3]" 00 00 00")) - format the time returned by mktime() function according to %W (the week number of the year)

  • q = int((d[2]+2)/3) - calculating the quarter number. The quarter is equivalent to 3 months. So we'll use 3 as a divisor.

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



来源:https://stackoverflow.com/questions/44214899/using-awk-how-to-convert-dates-to-week-and-quarter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!