DATA Step, Macro, Functions and more

How to convert from datetime16. to character mm/dd/yyyy with slashes

Accepted Solution Solved
Reply
New Contributor
Posts: 4
Accepted Solution

How to convert from datetime16. to character mm/dd/yyyy with slashes

I have a date (has month day year time) which Proc Contents says is datetime16. I want to convert it to a character string of format mm/dd/yyyy, with slashes and no time. 

I'm using SAS 9.4, 64bit, on a Mac through Parallels.


Accepted Solutions
Solution
‎07-31-2016 06:31 PM
Community Manager
Posts: 2,764

Re: How to convert from datetime16. to character mm/dd/yyyy with slashes

Create a new 10-byte char variable, and PUT the date part of the value using the MMDDYY10. format.  The DATEPART function will create the date value that you can format.

 

data want;
  set have; /* data with a datetime var, let's call it dt */
  length chardate $ 10;
  chardate = put(datepart(dt), mmddyy10.);
run;

But... why?  Perhaps just to export to something else for a text-based report?  While the value is in SAS, you can format and report/analyze without having to create a new variable.

View solution in original post


All Replies
Solution
‎07-31-2016 06:31 PM
Community Manager
Posts: 2,764

Re: How to convert from datetime16. to character mm/dd/yyyy with slashes

Create a new 10-byte char variable, and PUT the date part of the value using the MMDDYY10. format.  The DATEPART function will create the date value that you can format.

 

data want;
  set have; /* data with a datetime var, let's call it dt */
  length chardate $ 10;
  chardate = put(datepart(dt), mmddyy10.);
run;

But... why?  Perhaps just to export to something else for a text-based report?  While the value is in SAS, you can format and report/analyze without having to create a new variable.

New Contributor
Posts: 4

Re: How to convert from datetime16. to character mm/dd/yyyy with slashes

Thanks so much!
Super User
Posts: 10,516

Re: How to convert from datetime16. to character mm/dd/yyyy with slashes

If you are ever likely to want to sort on the data, or possibly group by month and year, or year and quarter or similar you might consider adding another date variable with the appropriate default format.

 

dateonly = datepart(datetimevariable);

format dateonly mmddyy10. ;

 

Using the dateonly variable for the x-axis of a graph will have values sort in chronologically. If you use a character then you get a sort order like: 01/01/2015, 01/01/2016, 01/02/2015, 01/02/2016 which is not often the desired appearance.

 

 

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 702 views
  • 0 likes
  • 3 in conversation