使用awk,如何将日期转换为星期和季度? [英] Using awk, how to convert dates to week and quarter?
问题描述
使用awk,如何将日期(yyyy-mm-dd)转换为星期和季度(将一周的第一天设置为星期一)?
Using awk, how to convert dates (yyyy-mm-dd) to week and quarter (first day of week set to monday)?
输入:
a;2016-04-25;10
b;2016-07-25;20
c;2016-10-25;30
d;2017-02-25;40
想要的输出:
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
推荐答案
awk 解决方案:
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
输出:
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($2,d,"-")
- split the 2nd field (date
) by separator-
mktime(datespec)
-将 datespec (日期规范)转换为时间戳mktime(datespec)
- turn datespec (date specification) into a timestampstrftime("%W", mktime(d[1]" "d[2]" "d[3]" 00 00 00"))
-根据%W
(一年中的星期几)格式化mktime()
函数返回的时间strftime("%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)
-计算季度号.该季度等于 3 个月.因此,我们将3作为除数.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
这篇关于使用awk,如何将日期转换为星期和季度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!