Home > Back-end >  Exporting csv file with datetime() in the name
Exporting csv file with datetime() in the name

Time:08-02

I am trying to export a csv file from SAS and adding datetime() to the name of the file. for some reason nothing happens. The export works fine but I don't get the time stamp in the file name.

This is how i create the datetime variable:

data Dato_eksport;
   dato_eksport=today();
   dato_eksport_f=datetime();
   format dato_eksport_f datetime19.;
run;

PROC SQL NOPRINT;
SELECT DISTINCT 
          dato_eksport_f
     
INTO      :dato_eksport_f
          
FROM Dato_eksport_F;

I the use this variable in my export:

%LET filtype_csv = .csv;
%LET filnavn_csv = CAT(OUTPUT_DAGLIG_LCR,&dato_eksport_f);
%LET path_csv = \\path\path\path\path\path\path\path;
%LET kombineret_csv = "&path_csv&filnavn_csv&filtype_csv" dlm = ';';
%PUT &kombineret_csv;

%ds2csv (
   data=OUTPUT_DAGLIG_LCR, 
   runmode=b, 
   csvfile=&kombineret_csv
 );

What am I doing wrong the file gets updated but I get no errors and the file is missing the datetime string. file export

I hope you cna point me in the right direction.

CodePudding user response:

First mistake is the PROC SQL step that is trying to create the macro variable dato_eksport_f is reading from a dataset you have not defined for us.

Second mistake is inserting text like CAT(...) into the macro variable filnavn_csv. To the macro processor everything is text, it only looks to operate on the text when it sees the macro triggers & or %.

To avoid adding leading/trailing spaces into the macro variable when using PROC SQL and the INTO clause make sure to add the TRIMMED keyword.

proc sql noprint;
select dato_eksport_f into :dato_eksport_f trimmed
  from Dato_eksport
;
quit;

There is no need to try to use functions to concatenate text in macro code. To append macro variables together just use the syntax you used in this statement:

%LET kombineret_csv = "&path_csv.\&filnavn_csv.&filtype_csv" dlm=';';

If you do want to use a SAS function in macro code you need to call it with the macro function %SYSFUNC(). You could use that to skip the data and proc sql steps and just call the DATETIME() function directly in macro code. Note that the leading space generated by the datetime19. format will be remove by the %LET statement.

%let dato_eksport_f = %sysfunc(datetime(),datetime19.);

Now you can build your full filename:

%LET path_csv = \\path1\path2\path3;
%LET filnavn_csv = OUTPUT_DAGLIG_LCR_&dato_eksport_f;
%LET filtype_csv = .csv;
%LET kombineret_csv = "&path_csv.\&filnavn_csv.&filtype_csv" dlm=';';
%PUT &kombineret_csv;

You might want to use a different string to timestamp your filenames. Something that avoids colons and also will sort properly.

data _null_;
  call symputx('dato_eksport_f'
              ,translate(put(datetime(),e8601dt.),'___','-T:'));
run;

Example:

1806  %put &=dato_eksport_f;
DATO_EKSPORT_F=2022_08_01_09_38_58
  • Related