Ladenkov Vladislav
Ladenkov Vladislav

Reputation: 1297

Convert date format to character string

I have a column of format DATETIME23. like this:

14.02.2017 13:00:25

I want to conver it to a string, so later, i would be able to modern it, so, for example, the final version would look like:

2017-02-14 13:00:25.000

Problem occures, when i try to convert date to char format: in result i have a string of smth like 1802700293 - which is the number of seconds.

I tried:

format date $23.0

or

date = put(date, $23.0)

P.S This is nother try:

data a;
format d date9.;
d = '12jan2016'd;
dtms = cat(day(d),'-',month(d),'-',year(d),' 00:00:00.000');

/* если нужно обязательно двухзначные день и месяц, то такой колхоз:  */
if day(d) < 10 then dd=cat('0',put(day(d),$1.)); 
else ddday=put(day(d),$2.);
if month(d) < 10 then mm=cat('0',put(month(d),$1.)); 
else mm=put(month(d),$2.);
yyyy=put(year(d),$4.);
/*dtms2 = cat(dd,'-',mm,'-',yyyy,' 00:00:00.000');*/
dtms2 = cat(dd,'-',mm,'-',yyyy,' 00:00:00.000');
dtms = cat(day(d),'-',month(d),'-',year(d),' 00:00:00.000');
run;

BUT, abnormally, the dtms2 concat destroys the zero in the month element

Upvotes: 0

Views: 4210

Answers (2)

Chris J
Chris J

Reputation: 7769

If your datetime is stored as a SAS datetime, just use the appropriate format :

data test ;
  dt = '09feb2017:13:53:26'dt ; /* specify a datetime constant */
  new_dt = put(dt,E8601DT23.3) ; /* ISO datetime format */
run ;

Output

     dt                new_dt

 1802267606    2017-02-09T13:53:26.000

If you need to replace the 'T' with a space, simply add a translate function around the put().

Upvotes: 1

Andrew Haynes
Andrew Haynes

Reputation: 2640

For your dtms solution you can use put and the Z2. format to keep the leading zero when you concatenate:

dtms = cat(day(d),'-', put(month(d),z2.),'-',year(d),' 00:00:00.000');

You should be able to just use put(date, datetime23.) for your problem though instead of $23, which is converting the number of seconds to a string with length 23. However, as a comment has mentioned datetime23. is not the format from your example.

Upvotes: 0

Related Questions