DATA Step, Macro, Functions and more

Add leading zeros to time variable

Reply
New Contributor
Posts: 3

Add leading zeros to time variable

Hi,

I have a time variable with the data as 03:45,1:25 etc with the length=15 and Char type. Can TOD5. be used for this time variable to add a leading zero which will make 1:25 as 01:25?

 

 

data Details;

attrib TIME_  length=$15 tod5.;

if TIME= ' ' then;

TIME_= put(TIME, tod5.);

run;

 

The above code is used,however does not change the values. Any suggestions would be of great help.

Thanks in advance.

 

Regards,

Rupa

Super User
Posts: 22,875

Re: Add leading zeros to time variable

Yes, you can, but you need to use INPUT to convert a character variable to a numeric variable. You also need to apply the format otherwise it's a number - the number of seconds.

 

*create sample data;
data have;
input time_char $;
cards;
03:45
1:25
;;;;
run;


data want; 
set have;
*convert to a numeric SAS time;
time_num = input(time_char, time.);
*format with format desired;
format time_num tod5.;
run;

*Print results to test;
proc print data=want;
run; 

@Rupa wrote:

Hi,

I have a time variable with the data as 03:45,1:25 etc with the length=15 and Char type. Can TOD5. be used for this time variable to add a leading zero which will make 1:25 as 01:25?

 

 

data Details;

attrib TIME_  length=$15 tod5.;

if TIME= ' ' then;

TIME_= put(TIME, tod5.);

run;

 

The above code is used,however does not change the values. Any suggestions would be of great help.

Thanks in advance.

 

Regards,

Rupa


 

New Contributor
Posts: 3

Re: Add leading zeros to time variable

Thanks Reeza, It worked.

Super User
Super User
Posts: 7,860

Re: Add leading zeros to time variable

This code doesn't make much sense.

data Details;
  attrib TIME_  length=$15 tod5.;
  if TIME= ' ' then;
  TIME_= put(TIME, tod5.);
run;

The $ in the value of the LENGTH means you are defining a character variable. You can't attach a numeric format like TOD to a character variable.  The IF statement doesn't make any sense because there is not statement to execute when the condition is true.  Perhaps you didn't mean to include the semi-colon ? Also you are not reading any data in this code.  Needs a SET or INPUT statement. Or at least an assignment statement to give TIME some value(s).

 

If you have a character variable now and what to keep it as character you could read the text into a time value and then write it back out using the TOD format?

if not missing(time) then time=put(input(time,time5.),tod5.);

Or if the issue is just that some values have 4 characters when the first value is less than 10 you could just add the zero.

if 4=length(time) then time='0'||time;
New Contributor
Posts: 3

Re: Add leading zeros to time variable

Thanks Tom

Ask a Question
Discussion stats
  • 4 replies
  • 109 views
  • 0 likes
  • 3 in conversation