将SAS字符转换为日期变量

huangapple go评论57阅读模式
英文:

Converting a SAS character to date variable

问题

我从Excel导入了一个包含日期和时间格式的日期变量。当我尝试使用SAS格式命令和输入函数重新格式化时,无法将变量转换为正确的格式。

在Excel中,日期显示为3/15/2021 1:00:00 PM,导入SAS后显示为44270.541666666664。

我需要它以任何日期格式显示。

我尝试在数据语句中使用格式:

data text1;
  set lib.text (drop = LoadFileName FirstName LastName PhoneNumber CreateBy);
  format LastAttemptDttm datetime.;
run;

在此之后,变量没有变化。

其中LastAttemptDttm是日期变量。此外,我还尝试了

data text1;
  set lib.text (drop = LoadFileName FirstName LastName PhoneNumber CreateBy);
  date_var = input(LastAttemptDttm, datetime.);
run;

之后,date_var被创建,但有0个观测。

我运行了proc contents来查看发生了什么,发现LastAttemptDttm被列为字符变量。

英文:

I imported date from excel with a date variable that is formatted with date and time. When I try to reformat using SAS format commands and input functions, nothing is able to convert the variable to the correct format.

The date in excel reads 3/15/2021 1:00:00 PM, when imported into SAS it reads 44270.541666666664.

I need it to be any format of date.

I tried using format in a data statement:

data text1; 
  set lib.text (drop = LoadFileName FirstName LastName PhoneNumber CreateBy);
  format LastAttemptDttm datetime.;
run;

There was no change in the variable after this.

where LastAttemptDttm is the date variable. In addition I also tried

data text1;
 set lib.text (drop = LoadFileName FirstName LastName PhoneNumber CreateBy);
 date_var = input(LastAttemptDttm, datetime.);
run;

After this, date_var was created, but had 0 observations.

I ran a proc contents to see what was going on, and LastAttemptDttm was listed as a character variable.

答案1

得分: 3

最好的方法是修复Excel表,使具有日期时间值的列不包含任何单元格中的字符串,而不是数字。然后,SAS将自动创建数值变量而不是字符变量。

但如果确实需要将字符串'44270.541666666664'转换为日期值,那么可以使用这个公式:

date = int(input(LastAttemptDttm, 32.)) + '30DEC1899'd;

如果想要转换为日期时间值,那么使用:

datetime = dhms(input(LastAttemptDttm, 32.) + '30DEC1899'd, 0, 0, 0);

确保将适当的显示格式附加到新的数值变量,以便日期(天数)或日期时间(秒数)的值以人们能够识别的样式打印出来。

英文:

The best thing is to fix the Excel sheet so that the column with the datetime value does not have any cells with strings instead of numbers. Then SAS will automatically create a numeric variable instead of character variable.

But if you do have to convert the string '44270.541666666664' into a date value then you can just use this formula

date = int(input(LastAttemptDttm,32.)) + '30DEC1899'd ;

If you want convert it to a datetime value instead then use:

datetime = dhms(input(LastAttemptDttm,32.) + '30DEC1899'd,0,0,0) ;

Make sure to attach the proper display format to the new numeric variable so the date (number of days) or datetime (number of seconds) values print in a style that humans can recognize.

huangapple
  • 本文由 发表于 2023年4月14日 00:08:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76007590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定