问题
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 timestampstrftime("%W", mktime(d[1]" "d[2]" "d[3]" 00 00 00"))
- format the time returned bymktime()
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