Search code examples
statastata-macros

Adding time in a file name


Consider the code snippet below:

local date: display %td_CCYY_NN_DD date(c(current_date), "DMY")
local date_string = subinstr(trim("`date'"), " " , "", .)
save "`date_string'_example", replace
mkdir "`date_string'_example"

This creates output as follows:

20170521_example.dta

However, I want to create a file name which also has time, not just date. If the time is 4PM 25 min 01 sec, then I wish to have the following:

20170521_162601_example.dta

How can I add this element?

I tried putting c(current_time) inside the date() function but that did not work.

Also, I tried to assign a local macro savedir using the date_string. However, it seems Stata can't recognise it when it is followed by \:

local date: display %td_CCYY_NN_DD date(c(current_date), "DMY")
local date_string = subinstr(trim("`date'"), " " , "", .)
local savedir "C:\Users\`date_string'_output"
cd "`savedir'

What should I do to save the local macro savedir?


Solution

  • You can get the desired output as follows:

    local datetime_string : display %tc_CCYYNNDD_HHMMSS clock(c(current_date) + " " + ///
                             c(current_time), "DMYhms")
    

    As regards to your second question, just replace \ in your file path with /.

    Forward slashes can be used in Stata for file paths on all operating systems, and Stata will take care to translate them correctly on Windows.