Search code examples
spss

SPSS - pass values of three dates fields into file name


My dataset has three date fields (adate10): Period, Version, and Created. The values for each field are identical for all cases. Let's say the values are:

Period = 10/01/17
Version = 11/15/17
Created = 11/25/17

I would like to pass all three dates into a SAVE OUTFILE='C:\Users\Inventory ? ? ?... command so the file name is:

C:\MyData\Inventory p20171001 v20171115 c20171125.sav

How I can pass the values of these three date fields into the save command? I assume Python is the way to go, but cannot figure out the syntax. I see several solutions at the link below, but they all involve only one date field; I have three. (And even when I tried with one date I couldn't get any of them to work).

http://spssx-discussion.1045642.n5.nabble.com/include-value-from-variable-in-filename-when-saving-td4326879.html


Solution

  • Here you go with a little Python:

    BEGIN PROGRAM.
    import spss, spssdata
    
    # names of date variables (case sensitive)
    varlist = ['period', 'version', 'created'] 
    
    # fetch dates from dataset and format them to YYYYMMDD
    data = spssdata.Spssdata(indexes=(varlist), cvtDates=(varlist))
    dates = [date.strftime("%Y%m%d") for date in data.fetchone()]
    data.close()
    
    # Create 'save command' command and submit it to spss
    spss.Submit(r"""
    SAVE OUTFILE = 'C:\MyData\Inventory p{0} v{1} c{2}.sav'.
    """.format(*dates))
    END PROGRAM.