Stata – Exporting dates in filenames

A key feature of writing long do-files is to export various outputs, logs, excel files, etc. at the end of your run. More often than not, it is useful to capture changes over time as data analysis progresses. It is therefore useful to export files and version control them with dates. A good practice is to save them in the format:


for example:


Keeping the year_month_day order ensures that files can be sorted easily and gives a much better progress order than for example, using filename_v1, filename_v2, etc.

A great feature of Stata is that it stores dates in a local:

display c(current_date)

If you add date to this prefix:

display date(c(current_date), "DMY") 

you, can now play around with Stata’s built-in date formats.

This allows us to rearrange the default date using the following command

local date: display %td_CCYY_NN_DD date(c(current_date), “DMY”)
display “`date'”

will show us today’s date in this format 2016 07 19

We need two fixes for this. First, is the leading blank before the year value 2016, which needs to be trimmed. Second the spaces need to be replaced with underscore (“_”) or hyphen (“-“) to make sure there are no spaces in the filename (always a good practice to have no spaces in filenames to avoid file import errors across softwares and operating systems).

This can be easily solved using the following:

local date = subinstr(trim("`date'"), " ", "_", .)
display "`date'"

which gives us 2016_07_19, the correct format we want.

This local can now be easily added to file exports:

graph export "mycoolgraph_`date'.png", replace

Leave a Reply

Your email address will not be published.