将'MM.YYYY'转换为像mmyy10这样的SAS日期格式

问题描述 投票:0回答:2

我有一个字符串'MM.YYYY',并希望将其转换为SAS中的日期格式 - 类似于format mmyy10.。我知道,因为我错过了一天,我不能使用任何SAS day format

现在我正在解决这个问题:

data testdate;

chardate = '06.2010';
ch_month = int(chardate);
ch_year = (chardate-ch_month)*10000;
date = mdy(ch_month,15,ch_year);
format date mmyy10.;

run;
proc print data=testdate;
run;

我有一个问题 - 这一年将比我预期的少一年。所以我的输出是06M2009 ?!我没有任何错误。这段代码有什么问题?另一件事 - 是否(我打赌有)更好/更好的方法来解决这个问题?

编辑:修复了MWE中的错误,感谢@Reeza

sas
2个回答
2
投票

只需使用INPUT()函数。添加一个月中的某一天,以便输入有效的日期值。

date = input('01.'||chardate,ddmmyy10.);

您的原始计算使用隐式类型转换,而不考虑浮点运算的使用。添加BEST32。格式以查看您的实际值。

data testdate;
  chardate = '06.2010';
  ch_month = int(chardate);
  ch_year = (chardate-ch_month)*10000;
  date = mdy(ch_month,15,ch_year);
  format _numeric_ best32. date yymmdd10.;
  put (_all_) (=);
run;

NOTE: Character values have been converted to numeric values at the places given by: (Line):(Column).
      108:17   109:18
chardate=06.2010 ch_month=6 ch_year=2009.99999999999 date=2009-06-15
NOTE: The data set WORK.TESTDATE has 1 observations and 5 variables.

尝试添加ROUND()函数调用

date = mdy(ch_month,15,round(ch_year,1));

2
投票

以下是将其转换为SAS日期的两种方法。即使未显示,SAS日期也必须具有“日期”组件。我在这里把它设置为1。

INPUT()将字符转换为数字以避免日志中的转换注释SUBSTR()从字符串中获取月/年。

date = mdy(input(substr(chardate, 2, 2), 8.), 1, input(substr(chardate, 4, 4), 8.));

或者另一种方法是直接使用INPUT。首先使用COMPRESS()函数删除句点,然后将01连接到日期的开头,并将其作为DDMMYY格式化日期读取。

date2 = input(compress('01'||chardate, "."), ddmmyy10.);

完整代码在这里:

data testdate;

chardate = '06.2010';
date = mdy(input(substr(chardate, 2, 2), 8.), 1, input(substr(chardate, 4, 4), 8.));

date2 = input(compress('01'||chardate, "."), ddmmyy10.);

format date: mmyy10.;

run;
proc print ;
run;

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.