## Parsing a Date/Time

Solved
Occasional Contributor
Posts: 9

# Parsing a Date/Time

I'm trying to parse dates and times in sas.

So for instance I'd like to be able to parse this date 1/20/2012, I tried substr to get what I'm looking for along the lines of:

Month = substr(Date, 1,1);

Day = substr(Date,3,4);

Year = substr(Date,6,9);

This did not work

I would also like to parse time as well: 5:00:00 PM, it seems that substr doesn't work on this as well.

such that I'd get

Hour = 5

Minute = 0

Any suggestions?

Accepted Solutions
Solution
‎12-05-2013 09:01 PM
Frequent Contributor
Posts: 87

## Re: Parsing a Date/Time

Depends if number is stored as SAS date with a format on it. If it's stored as a character string then:

data want ;

length day month \$2 year \$4 ;

set have ;

day = scan(date,2,'/') ;

month = scan(date,1,'/') ;

year = scan(date,3,'/') ;

run ;

If as a date then:

data want ;

set have ;

day = day(date) ;

month = month(date) ;

year = year(date) ;

run ;

Similarly:

data want ;

set have ;

hour = hour(time) ;

minute = minute(time) ;

run ;

data want ;

length hour minute \$2 ;

set have ;

hour = scan(time,1,':') ;

minute = scan(time,2,':') ;

run ;

All Replies
Posts: 3,852

## Re: Parsing a Date/Time

The third argument to substr is LENGTH.  You would do better with SCAN function.  Or better still read the dates and times and SAS dates and times then you get a suite of very nice functions to do all kinds if things.  Like pick out the day month or year.

Solution
‎12-05-2013 09:01 PM
Frequent Contributor
Posts: 87

## Re: Parsing a Date/Time

Depends if number is stored as SAS date with a format on it. If it's stored as a character string then:

data want ;

length day month \$2 year \$4 ;

set have ;

day = scan(date,2,'/') ;

month = scan(date,1,'/') ;

year = scan(date,3,'/') ;

run ;

If as a date then:

data want ;

set have ;

day = day(date) ;

month = month(date) ;

year = year(date) ;

run ;

Similarly:

data want ;

set have ;

hour = hour(time) ;

minute = minute(time) ;

run ;

data want ;

length hour minute \$2 ;

set have ;

hour = scan(time,1,':') ;

minute = scan(time,2,':') ;

run ;

Occasional Contributor
Posts: 9

## Re: Parsing a Date/Time

SteveNZ,

Thanks for your response the code you provided work well. It accomplished what I needed it to.

🔒 This topic is solved and locked.