AngryWhopper
AngryWhopper

Reputation: 433

Convert ugly string to a date

I have some datetimes in data set as ugly strings.

Example: "Saturday 14 Jan 2017 00:00:00"

I would like to convert this into a date, e.g. 2017JAN14

Any simpler solution then going down the regular expression route?

Upvotes: 0

Views: 96

Answers (1)

user667489
user667489

Reputation: 9569

If you want exactly yyyymmmdd then you'll need to create your own format to do that, but you're happy with a builtin then the following should do. Just skip the day of the week and convert the rest using an informat:

data _null_;
mytxtdate = "Saturday 14 Jan 2017 00:00:00";
mydate = input(compress(substr(mytxtdate,index(mytxtdate,' '))),date9.);
format mydate yymmdd10.;
put _all_;
run;

This certainly is awkward. I'd be interested to know if there's a way of doing this as a one-liner using fewer than 4 data step functions. The logic here is:

  • Skip to the first space using index.
  • Remove all spaces in the string from that point onwards using substr and compress
  • Input as a SAS date using the date9. informat, which will look at just the first 9 characters of the resulting string and ignore the rest.

Upvotes: 2

Related Questions