Reputation: 2638
This code from Raynald's SPSS Tools successfully adds the system date to an output filename, but the date comes out formatted like this:
filename_20-MAR-23.sav
I need to add the current date to output filenames using the format yyyy-mm-dd, like this:
filename_2023-03-20.sav
The syntax reference file for my installation (SPSS 27) includes the date format YMDHMS which looks more like what I need, but I only want the date, not the time:
I have tried substituting YMDHMS and other date format syntax into Raynald's code, but nothing has worked so far. Does anyone know how to do this? Thank you!
Here is the code for reference:
* Objective: Save data file with the current date as part of the name.
* [email protected] 2004/05/24.
* Define dummy data .
DATA LIST FREE /a.
BEGIN DATA
1 2 3
END DATA.
* Define a macro which will yield the current date.
STRING #cdate(A9).
COMPUTE #cdate=$DATE.
DO IF $casenum=1.
WRITE OUTFILE 'c:\\temp\\temp.sps' /"DEFINE !date()'"#cdate"'!ENDDEFINE.".
END IF.
EXECUTE.
* Run the macro.
INCLUDE 'c:\\temp\\temp.sps'.
SAVE OUTFILE='c:\\temp\\example1_' + !date + '.sav'.
Upvotes: 1
Views: 467
Reputation: 2638
This can also be done by running a short python script within SPSS syntax.
begin program python3.
import time, spss
spss.SetMacroValue("!timestamp", "'" + time.strftime("%Y-%m-%d") + "'")
end program.
save outfile = "C:\temp\Python_timestamp_2_" + !timestamp + ".sav".
Upvotes: 1
Reputation: 11350
Once you've computed #cdate
you can change it into a date variable (right now it's a string), then change it's format, then back to a string in order to optimize it:
cd "C:\Users\eli\work\seker tool".
DATA LIST FREE /a.
BEGIN DATA
1 2 3
END DATA.
* Define a macro which will yield the current date.
string #dtt(a11).
compute #dtt=replace(concat("_", string(number($DATE, DATE9), SDATE10)), "/","-").
DO IF $casenum=1.
WRITE OUTFILE 'temp.sps' /"DEFINE !date()'"#dtt"'!ENDDEFINE.".
END IF.
EXECUTE.
* Run the macro.
INCLUDE 'temp.sps'.
*now get back to your original dataset and save it.
dataset activate YourOriginalDataset.
SAVE OUTFILE='YourDataName' + !date + '.sav'.
Now if the original date cdate
was "21-MAR-23" the new one dtt
is "_2023-03-21" and will show like that in the file name.
NOTE - in the original code you use #
in the beginnig of variable names - that's nice to avoid cluttering your work data, but since all this procedure is happening on an independent temporary dataset, you'd do better without them - debugging is easier when you can actually see your data :)
Upvotes: 1