我无法弄清楚如何计算时间变量的持续时间 关于如何解决这个问题的任何想法?
答案 0 :(得分:1)
编码为整数h,hmm的军事时间值可以通过将数字转换为SAS时间值然后使用某些假设执行delta计算来处理。
data sleep_log;
input name $ boots_down boots_up;
datalines;
Joe 2000 0600 slept over midnight
Joe 1000 1230 slept into lunch
Joe 1630 1700 30 winks
Joe 0100 0100 out cold!
run;
data sleep_data;
set sleep_log;
down = hms(
int(boots_down / 100) /* extract hours */
, mod(boots_down , 100) /* extract minutes */
, 0 /* seconds not logged, use zero */
);
up = hms(
int(boots_up / 100) /* extract hours */
, mod(boots_up , 100) /* extract minutes */
, 0 /* seconds not logged, use zero */
);
* SAS time values are linear and simple arithmetic can apply;
if up <= down
then delta = '24:00't + up - down; /* presume roll over midnight */
else delta = up - down;
format down up delta time5.;
run;
更强大的日志也会记录当天,消除假设并提供适当的时间维度。
答案 1 :(得分:1)
您可以从数字军事时间HHMM中提取小时和分钟,然后使用HMS()
功能创建SAS时间。
HMS(Hour,Minute,Second)
,DHMS(date,hour,minute,second)
完整代码:
data have;
input sleep awake date_s date_w;
informat date_s date9. date_w date9.;
format sleep z4. awake z4. date_s date9. date_w date9.;
datalines;
2300 0500 12feb2018 13feb2018
2000 0300 11feb2018 12feb2018
0530 1230 10feb2018 10feb2018
;
run;
data want;
set have;
new_sleep_time=hms(int(sleep/100),int(mod(sleep,100)),0);
new_awake_time=hms(int(awake/100),int(mod(awake,100)),0);
dt_awake=dhms(date_w,hour(new_awake_time),minute(new_awake_time),0);
dt_sleep=dhms(date_s,hour(new_sleep_time),minute(new_sleep_time),0);
diff=dt_awake-dt_sleep;
keep new_sleep_time new_awake_time dt_awake dt_sleep diff;
format new_sleep_time time8. new_awake_time time8. diff time8. dt_awake datetime21. dt_sleep datetime21.;
run;
输出:
new_sleep_time=23:00:00 new_awake_time=5:00:00 diff=6:00:00 dt_awake=13FEB2018:05:00:00 dt_sleep=12FEB2018:23:00:00
new_sleep_time=20:00:00 new_awake_time=3:00:00 diff=7:00:00 dt_awake=12FEB2018:03:00:00 dt_sleep=11FEB2018:20:00:00
new_sleep_time=5:30:00 new_awake_time=12:30:00 diff=7:00:00 dt_awake=10FEB2018:12:30:00 dt_sleep=10FEB2018:05:30:00