Home > Net >  get start date of week from week number and year only
get start date of week from week number and year only

Time:11-11

I have a dataset where the data is reported by week and year like: YYWW. I have split it into to columns: Year and Week.

I need to get a date from the week: Week_start_date. My weeks start at mondays, so I would like to get the monday and sunday date from each week.

ID YYWW year week Week_start_date Week_end_date
1 1504 2015 04 ? ?
2 1651 2016 51 ? ?
3 1251 2012 51 ? ?
4 1447 2014 47 ? ?

How do I extract the week start date from just a week number and year? I've looked at several threads at SO, but haven't found a solution yet.

I have tried looking at different threads, but encounters problems using their solutions. Most seaches for "convert week number and year to date" on google and SO returns the opposite: Getting a weeknumber from a date. This guy answered by Vince, have maybe some similar issues, but I can't get the code to do the job: https://communities.sas.com/t5/SAS-Programming/Converting-week-number-to-start-date/td-p/106456

CodePudding user response:

Use INTNX() with the WEEK interval and increment from the first of the year. Use 1 to get Monday/Sunday dates.

You may need to tweak to match the dates you need.

data have;
infile cards dlm='09'x;
input ID $  YYWW    year    week ;
format year 8. week z2.;
cards;  
1   1504    2015    04  
2   1651    2016    51  
3   1251    2012    51  
4   1447    2014    47
;;;;

data want;
set have;
    week_start = intnx('week', mdy(1, 1, year), week, 'b') 1;
    week_end = intnx('week', mdy(1, 1, year), week, 'e') 1;
    format week_: date9.;
run;

CodePudding user response:

Use one of the WEEK... informats. But you will need to insert the letter W between the YEAR and WEEK number.

data have;
  input ID $  YYWW    year    week ;
cards;  
1 1504 2015 04
2 1651 2016 51
3 1251 2012 51
4 1447 2014 47
;;;;

data want;
  set have;
  week_start=input(cats(year,'W',put(week,Z2.)),weekv.);
  week_end=week_start 6;
  format week_: yymmdd10.;
run;

Results

Obs    ID    YYWW    year    week    week_start      week_end

 1     1     1504    2015      4     2015-01-19    2015-01-25
 2     2     1651    2016     51     2016-12-19    2016-12-25
 3     3     1251    2012     51     2012-12-17    2012-12-23
 4     4     1447    2014     47     2014-11-17    2014-11-23
  • Related