Sending automated email from SAS with attachments that changes name - email

I have files that should be send out every week. These files changes names e.g. "filename_1" next week it will be "filename_2".
But it only takes the filename that I manually wrote which is filename_1. Is there a way to say that it should take the latest file with this name everyweek,instead of me doing it manually every week?
This is my code for the email (I manually wrote the filename):
filename outbox email from="test#test.dk" to="test#test.dk"
type='text/html' subject='test' attach=("F:\filename_1.png" ct='png')
ods html body=outbox rs=none style=Htmlblue;run; ods html close;

The SAS macro facility will help you solve this very problem. If your filenames always have a consistent pattern, you can assign a macro variable to automatically change it for you. For simplicity's sake, let's say your filename always ends with today's date. You can assign a macro variable to hold this value.
%let filename = filename_&sysdate9..png;
This will resolve to filename_14DEC2020.png. You can confirm it with %put &filename.
If your file is sent out weekly and increments in a pattern, some quick math will help us figure out the correct suffix. Let's set a base week to start. We can count the number of weeks from this base week to identify the suffix. In this case, let's say it's today: December 14th, 2020. intck() can count the number of weeks from then until today. Our logic is:
suffix = (Number of weeks from Dec. 14th 2020 to Today) + 1.
In data step language, this is:
suffix = intck('week', '14DEC2020'd, today() ) + 1;
Translated to SAS macro language:
%let suffix = %sysevalf(%sysfunc(intck(week, %sysfunc(inputn(14DEC2020, date9.)), %sysfunc(today()) )) + 1);
%let filename = filename_&suffix..png;
Because we're pulling from data step functions, we need to enclose nearly everything in %sysfunc() to call them. This is one of the functions available that connect the SAS macro facility with the data step language.
Note that we also cannot use date literals directly in the SAS macro facility. We must use inputn() or putn() to convert a human-readable date into a SAS date format.
Simply call this macro variable within your code and it will resolve automatically (except within single quotes).
filename outbox email
from="test#test.dk" to="test#test.dk"
type='text/html'
subject='test'
attach=("F:\&filename" ct='png')
;

Related

How do I convert Stata dates (%td format e.g. 30jan2015) into YYYYMMDD format (e.g. 20150130)

* date is in %td format
gen date1 = real(string(mofd(daily(date, "DMY")), "%tmCYN"))
* type mismatch error
tostring date, gen(dt)
gen date1 = real(string(mofd(daily(dt, "DMY")), "%tmCYN"))
* the code runs but generates no results
tostring date, gen(dt)
gen date2=date(dt, "YMD")
* the code runs but generates no results
If a date variable has a display format %td it must be numeric and stored as some kind of integer. The display format is, and is only, an instruction to Stata on how to display such integers. Confusions about conversion often seem to hinge on a misunderstanding about what format means, as format is an overloaded word in computing, referring variously to file format (as in graphics file format, .png or jpg or whatever); data layout (as in wide or long layout, structure or format); variable or storage type; and (here) display format. There could well be yet other meanings.
A date displayed as 30jan2015 is stored as an integer, namely
. display mdy(1, 30, 2015)
20118
and a glance at help data types shows that your variable date could be stored as an int, float, long or double. All would work, although int is least demanding of memory. You would need (e.g.) to run describe date to find out which type is being used in your case, but nothing to come in this answer depends on knowing that type. Note that finding out what Stata is doing and thinking can be illuminated by running display with simple, single examples.
Your question is ambiguous.
Want to change display format? If you wish merely to see your dates in a display format exemplified by 20150130 then consulting help datetime display formats shows that the display format is as tested here with display, which can be abbreviated all the way down to di
. di %tdCCYYNNDD 20118
20150130
so
format date %tdCCYYNNDD
is what you need. That instructs Stata to change the display format, but the numbers stored remain precisely as they were.
Want such dates as variables held as integers? If you want the dates to be held as integers like 20150130 then you could convert it to string using the display format above, and then to a real value. A minimal sandbox dataset shows this:
. clear
. set obs 1
Number of observations (_N) was 0, now 1.
. gen date = 20118
. gen wanted = real(strofreal(date, "%tdCCYYNNDD"))
. format wanted %8.0f
. l
+------------------+
| date wanted |
|------------------|
1. | 20118 20150130 |
+------------------+
A display format such as %8.0f is needed to see such values directly.
Another method is to generate a large integer directly. You need to be explicit about a suitable storage type and (as just mentioned) need to set an appropriate format, but it can be got to work:
. gen long also = 10000 * year(date) + 100 * month(date) + day(date)
. format also %8.0f
Want such dates as variables held as strings? This is the previous solution, but leave off the real(). The default display format will work fine.
. gen WANTED = strofreal(date, "%tdCCYYNNDD")
. l
+-----------------------------+
| date wanted WANTED |
|-----------------------------|
1. | 20118 20150130 20150130 |
+-----------------------------+
I have not used tostring here but as its original author I have no bias against it. The principles needed here are better illustrated using the underlying function strofreal(). The older name string() will still work.
Turning to your code,
tostring date, gen(dt)
will just put integers like 20118 in string form, so "20118", but there is no way that Stata can understand that alone to be a daily date. You could have run tostring with a format argument, which would have been equivalent to the code above. The advantage of tostring would only be if you had several such variables you wished to convert at once, as tostring would loop over such variables for you.
I can't follow why you thought that conversion to a monthly date or use of a monthly date display format was needed or helpful, as at best you'd lose the information on day of the month. Thus at best Stata can only map a monthly date back to the first day of that month, and at worst a monthly date (here 660) could not be understood as anything you want.
. di mofd(20118)
660
. di %td mofd(20118)
22oct1961
. di %td dofm(mofd(20118))
01jan2015
There is no shortcut to understanding how Stata thinks about dates that doesn't involve reading the needed parts of help datetime and help datetime display formats.
Yet more explanation and examples can be found at https://www.stata-journal.com/article.html?article=dm0067

SAS: Get current year in YY format

I want to assign the current year in a YY format to either a macro or data set variable.
I am able to use the automatic macro variables &sysdate or &sysdate9 to get the current date. However, extracting the year in a YY format is proving to be a nightmare. Below are some examples of what I've been trying.
There exists the YEARw. format. But when I try to use it I get errors or weird results. For instance, running
data _null_;
yy = year(input("&sysdate9.", year2.));
put yy=;
run;
produces the error
ERROR 48-59: The informat YEAR was not found or could not be loaded.
If I try to format the variable in the output, I get 1965 instead of the current year. The following
data _null_;
yy = year(input("&sysdate9.", date9.));
put yy= yy year2.;
run;
outputs
yy=2016 65
Please help.
This works to get you the 2-digit year number of the current year:
DATA _NULL_;
YEAR = PUT(TODAY(),YEAR2.);
PUT YEAR;
RUN;
/* Returns: 16 */
To breakdown what I am doing here:
I use TODAY() to get the current date as a DATE type. &SASDATE needs to be converted to a DATE, but also it is the date that the SAS session started. TODAY() is the current date.
PUT allows us to pass in a non-character (numeric/date) value, which is why it is used with TODAY() as opposed to INPUT.
I think it is worth exploring the issues here in more detail.
First, Formats are patterns for converting numeric values to a human readable format. That's what you want to do here: convert a date value to a human readable format, in this case to a year.
Informats, on the other hand, convert human readable information to numeric values. That's not what you're doing here; you have a value already.
Second, put matches with Formats, and input matches with informats, exclusively.
Third, you get close in your last try: but you misuse the year format. Formats are basically value mappings, so they map every possible numeric value in their range (sometimes "all values" is the range, sometimes not) to a display value (string). You need to know what kind of value is expected on the input. YEARw. expects a date value as input, not a year value: meaning input is "number of days from 1/1/1960", mapped to "year". So you cannot take a value you've already mapped to a year value and map it again with that method; it will not make any sense.
Let's look at it:
data _null_;
yy = year(input("&sysdate9.", date9.));
put yy= yy year2.;
run;
yy contains the result of the year function - 2016. Good so far. Now, you need the 2 digit year (16); you can get that through mod function, if you like, or put/substr/input:
data _null_;
yy = input(substr(put(year(input("&sysdate9.", date9.)),4.),3,2),2.);
put yy=;
run;
mod is probably easier though since it's a number. But of course you could've used year:
data _null_;
yy = put(input("&sysdate9.", date9.),year2.);
put yy=;
run;
Now, yy is character, so you could wrap that with input(...,2.) or leave it character depending on your purposes.
Finally - a use note on &sysdate9.. You can easily make this a date without input:
"&sysdate9."d
So:
yy = put("&sysdate9."d,year2.);
That's called a date literal (and "..."dt and "..."t also work for datetime,time). They require things in the standard SAS formats to work properly.
And as pointed out in Nicarus' answer, today() is a bit better than &sysdate9 since it is guaranteed to be today. If you're running this in batch or restart your session daily, this won't matter, but it will if you have a long-running session.
Apply the year function to the date variable
Convert to string
Take last 2 digits
EDIT: change input to PUT
Year = substr(put(year(today()), 4.), 3);

How to format input for SAS's MONYY format

I currently have a dataset with dates in the format "FY15 FEB". In attempting to format this variable for use with SAS's times and dates, I've done the following:
data temp;
set pre_temp;
yr = substr(fiscal,3,2);
month = substr(fiscal,6,length(fiscal));
mmmyy = month||yr;
input mmmyy MONYY5.;
datalines;
run;
So, I have the strings representing the year and corresponding month. However, running this code gives me the error "The informat $MONYY was not found or could not be loaded." Doing some background on this error tells me that it has something to do with passing the informat a value with the wrong type; what should I alter in order to get the correct output?
*Edit: I see on the SAS support page for formats that "MONYYw. expects a SAS date value as input;" given this, how do I go from strings to a different date format before this one?
When you see a $, it means character value. In this case, you're feeding SAS a character value and giving it a numeric format. SAS inserts the $ for you, but there is no such format in existence.
I'm going to ignore the datalines statement, because I'm not sure why it's there (though I do notice there is no set statement). You might have an easier time just changing your program to:
data temp;
yr = substr(fiscal,3,2);
month = substr(fiscal,6,length(fiscal));
pre_mmmyy = strip(month)||strip(yr);
mmmyy=input(pre_mmmyy,MONYY5.);
run;
you can also remove the "length(fiscal))" from the substring function. The 3rd argument to the substring function is optional, and will go to the end of the string by default.

Failed to change character into date in SAS

I imported 5 excel files into SAS and there are some dates formatted as 8/3/1989 originally and formatted into 03Aug1989 (DATE9.) which is what I really want. However, on 1 file the dates failed to converted into DATE9. and it is read as $CHAR10 when I read the log. I tried several ways to reformat it into DATE9 but failed.
I tried to change all informat/format/input into DATE9. instead of $CHAR10 but failed, the results are all empty (.)
I tried DateNew=input (Date,DATE9.); but it didn't work either.
Any comment?
Thanks!
Joe's suggestion in the comment should be plan A. But occasionally built-in SAS format-specifying options don't work and you still end up with a string. If that's where you're at, here's a good fallback:
data test;
format imported_date $char10.;
imported_date = "8/3/1989";
month = scan(imported_date, 1, "/")*1;
day = scan(imported_date, 2, "/")*1;
year = scan(imported_date, 3, "/")*1;
date_datefmt = mdy(month,day,year);
format date_datefmt date9.;
run;

Macro variable creation based on date value in SAS

I have a list of company IDs and Dates and I want to run a macro on this list in such a way that for each date all the company IDs need to be considered as my macro filter.
For example, my list is -
DATA comp_date_list;
INPUT compno sdate;
DATALINES;
12490 20090120
87432 20090120
24643 20090120
87432 20090119
12490 20090105
24643 20090105
;
proc print data=comp_date_list;
run;
Now, I have a macro that is as follows -
%macro1(compno=,sdate=,threshold=,fdate=,edate=)
Now The macro has to run for every comp-date combination in my list. But since this is to run on a very large dataset, running it n times will take a long time. So to reduce the runtime, I plan to make a list of compnos for a given date and alter my macro to produce the results for a date.
Now my question is how to create a macro variable that has all the compnos for a given date and which alters as date changes? am new to macro writing and SAS. So please excuse my ignorance. Thanks!
A call execute statement in a datastep can run selective code (in this case, your macro) after the datastep in which it was called. For example, the following should work for you:-
proc sort data = comp_date_list;
by sdate compno;
data _null_;
set comp_date_list;
by sdate;
attrib all_comps_on_date length=$1000 label="All_comps_on_date: '|' separated company numbers for date";
retain all_comps_on_date "";
if first.sdate then all_comps_on_date = '';
all_comps_on_date = catx('|', all_comps_on_date, compno);
if last.sdate then call execute('%macro1(compno='||strip(all_comps_on_date)||',sdate=,threshold=,fdate=,edate=)');
run;
A note of caution though; call execute can play havoc with macros that themselves create macro variables (especially if they are using call execute statements!)
I can only echo #ChrisJ and add that while SAS macros can be useful, maintaining and debugging them is a pain and I only use them as a last resort. Not much help of course with legacy code!