【问题标题】:changing date formats to YYMMDD8. in SAS for date calculations将日期格式更改为 YYMMDD8。在 SAS 中用于日期计算
【发布时间】:2014-08-08 22:23:17
【问题描述】:

我的数据集中有一个日期变量(当前为数字),它具有三种类型的日期:

  1. 只是年份(yyyy)

  2. 年/月 (yyyymm)

  3. 年/月/日 (yyyymmdd)

我正在尝试将仅包含年份的日期转换为 1 月 1 日,并将具有年份/月份的日期转换为月份的第一天,以便我可以从数据集中另一个日期变量中减去日期yymmdd8 格式的日期(与#3 相同)。我在数据步骤中尝试了这个,但它不起作用:

if length(Date)=4 then DateF=mdy(1,1,substr(Date,1,4));  
if length(Date)=6 then DateF=mdy(substr(Date,5,2),1,substr(Date,1,4));  
if length(Date)=8 then DateF=mdy(substr(Date,5,2),substr(Date,7,2),substr(Date,1,4));  
Date2=input(put(DateF,8.),YYMMDD8.);  
format Date2 YYMMDD8.;

谁能告诉我我的代码有什么问题?谢谢!

【问题讨论】:

  • 你确定变量是数字的吗?我认为数字变量不能以不同的格式显示。
  • 这就是它在 proc 内容上显示的内容。即使不是我认为 input(put(variable)) 可以将变量更改为数字。我应该尝试使用字符变量吗?
  • 哦我现在明白了...没有/ 字符-只有数字字符...

标签: date format sas


【解决方案1】:

因此,要调试您的代码,您可以先尝试将您的一些假设打印到屏幕上。我将首先打印您的if 语句的结果...

data blah;

  format date best.;

  input date; 

  test1 = length(date);
  put test1=;

datalines;
  2014
  201408
  20140829
;
run;

这给出了:

test1=12
test1=12
test1=12

显然不是我们所期望的。自动转换为字符变量后,看起来数字字段的长度为 12 个字符,并且在转换时,它在前面用空格填充。我们可以通过将 put 语句替换为:

test2 = "*" || length(cats(date)) || "*";
put test2=;

打印出来:

test2=*           4*
test2=*           6*
test2=*           8*

所以我们需要做的是不要依赖自动类型转换,因为这不仅会影响if 条件,还会影响substr() 函数。相反,我们将自己做:

data blah;

  format date best.;


  input date; 

  tmp_date = cats(date);


  if length(tmp_Date)=4 then DateF=mdy(1,1,substr(tmp_Date,1,4));  
  if length(tmp_Date)=6 then DateF=mdy(substr(tmp_Date,5,2),1,substr(tmp_Date,1,4));  
  if length(tmp_Date)=8 then DateF=mdy(substr(tmp_Date,5,2),substr(tmp_Date,7,2),substr(tmp_Date,1,4));  

  format Datef YYMMDD8.;

datalines;
  2014
  201408
  20140829
;
run;

cats() 函数将为我们进行转换,并修剪前导和尾随空格!它非常有用...无论如何希望能解释出了什么问题以及您将来如何调试自己的代码=)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多