Save Histograms with date/time appended to filename

Hello everyone;

This is probably more of a coding question than anything, but I’m attempting to save a histogram with the local date & time appended to the output filename. I’ve been trying to play with things like strftime with parameters ("%Y%m%d_%H%M%S") or TDatime to no avail. Here’s a part of the code where I think the format of date/time should be inserted:

-----after filling histogram—

c1->SaveAs(“slope” + (date/time string??)** + “.png”);

**is this legal to insert a string for the date/time here?

It takes const char *. You can use for example an array of char that you fill before doing SaveAs, or use Form directly inside SaveAs (e.g. SaveAs(Form("%s...%s","slope",...,".png")).

Hey @dastudillo, thank you for the info! I’m running into some errors, and I’m sure it’s due to me being new to coding.

If you have a free sec, I just have a few questions: I’d like to actually use the Form() directly inside SaveAs. Upon attempting several things, I’m finding that the %s…%s is the designator that tells the function we’re printing a string using the following strings separated by commas (I hope this is correct–this is what it seems like to me at least). The difficult part for me is figuring out exactly what to do in order to place a time character string inside this guy. This is what I’ve attempted, and the output is directly beneath:


time_t t;
struct tm *tmp;
char MY_TIME[20];
time( &t );
tmp = localtime( &t );

strftime(MY_TIME, 20, “%Y%m%d_%H%M%S”, tmp);

c1->SaveAs(Form("%s %s",“slope_v_endcap_”, MY_TIME , “.png”));


slope_v_endcap_20210810_131643 (lacking .png)!

The warning I get is this:

warning: data argument not used by format string [-Wformat-extra-args] (i.e. pointing to the ‘’ before .png)


I tried that but also got an error, @Wile_E_Coyote! I did however figure it out! Thank you guys!

I ended up doing this:

c1->SaveAs(Form("%s%s.png",“slope_v_endcap_”, MY_TIME));

Worked a treat!

I have an extracurricular Q though, if you guys wouldn’t mind–is there a way to keep all of this formatting, but just introduce a directory header. In other words, saving this output file name exactly as it is but ensuring it makes it into a directory (or makes a directory if the directory doesn’t yet exist)?

const char *MY_DIR = "some/sub/directory";
gSystem->mkdir(MY_DIR, kTRUE);
c1->SaveAs(Form("%s/slope_v_endcap_%s.png", MY_DIR, MY_TIME));

Worked perfectly–thank you so much; you guys have been super helpful!