Convert character time to numeric

Solved
Occasional Contributor
Posts: 7

Convert character time to numeric

This is the question:

Z is a character variable whose value takes the form "x hr y min" for different integers x and y. Create a numeric variable X5 storing the corresponding number of minutes. For example if Z is "2 hr 25 min", then X5 should be 145.

I have had problems when time was displayed with : (ex: 9:30:30) or AM/PM (9:30 AM), but I never encountered this kind. How do I approach such problem? T

Accepted Solutions
Solution
‎02-25-2014 09:04 AM
Frequent Contributor
Posts: 106

Re: Convert character time to numeric

data have;

input time \$50.;

if countw(time,': ')>=3 then

num=input(scan(time,1,': '),2.)*60+input(scan(time,3,': '),2.);

else

num=input(scan(time,1,': '),2.)*60+input(scan(time,2,': '),2.);

cards;

2 hr 25 min

1:30:30

9:30:30

9:30

00:12

1 hr 10 min

;

run;

output:

Obs    time           num

1     2 hr 25 min    145

2     1:30:30         90

3     9:30:30        570

4     9:30           570

5     00:12           12

6     1 hr 10 min     70

All Replies
Super Contributor
Posts: 543

Re: Convert character time to numeric

Hi.

Here is one poorly written way:

data in;

Z =  "2 hr 25 min";

hr = input(scan(z, 1,"hr"), 8.);

min = input(

tranwrd(

reverse(

scan(

reverse(z), 1,"rh")

),

"min",""),

8.);

/* "nim 52 rh 2"*/

/* 25 min*/

time_in_Min = hr*60+min;

run;

Occasional Contributor
Posts: 7

Re: Convert character time to numeric

Thank :smileygrin:

Super Contributor
Posts: 1,636

Re: Convert character time to numeric

data have;

time='2 hr 25 min';

num=input(scan(time,1),2.)*60+input(scan(time,3),2.);

proc print;run;

Occasional Contributor
Posts: 7

Re: Convert character time to numeric

Thanks :smileygrin:

Super Contributor
Posts: 578

Re: Convert character time to numeric

data have;

input x txt1 \$ y txt2 \$;

z=x*60 + y;

cards;

2 hr 25 min

;

run;

Occasional Contributor
Posts: 7

Re: Convert character time to numeric

Thanks :smileygrin:

Solution
‎02-25-2014 09:04 AM
Frequent Contributor
Posts: 106

Re: Convert character time to numeric

data have;

input time \$50.;

if countw(time,': ')>=3 then

num=input(scan(time,1,': '),2.)*60+input(scan(time,3,': '),2.);

else

num=input(scan(time,1,': '),2.)*60+input(scan(time,2,': '),2.);

cards;

2 hr 25 min

1:30:30

9:30:30

9:30

00:12

1 hr 10 min

;

run;

output:

Obs    time           num

1     2 hr 25 min    145

2     1:30:30         90

3     9:30:30        570

4     9:30           570

5     00:12           12

6     1 hr 10 min     70

Frequent Contributor
Posts: 106