How to save current time in file name
127 views (last 30 days)
Show older comments
Hi,
since MATLAB function datestr is now not recommended, I wanted to try saving with datetime. Unfortunately I keep getting errors.
What I used before:
filename = ['output ' datestr(now,'yyyy-mm-dd_HH_MM_SS') '.mat'];
save(filename,'-v7.3')
What I tried now:
filename = ['output ' string(datetime('now')) '.mat'];
save(filename,'-v7.3')
I wanted it in the 'yyyy-mm-dd_HH_MM_SS' format, but it's not that important.
The error I keep getting is:
"Error using save.
Argument must be a text scalar."
I also tried different things (what was shown in HELP) such as these
filename = ['output ' string(datetime('now'), 'yyyy-MM-dd hh:mm:ss') '.mat'];
filename = ['output %d .mat', string(datetime('now'), 'yyyy-MM-dd hh:mm:ss')];
or to separate it with commas, but nothing I come up with works. Can you guys help?
0 Comments
Accepted Answer
Stephen23
on 15 Jan 2024
Edited: Stephen23
on 15 Jan 2024
You are trying to concatenate STRINGS... and that gives you STRING array with multiple elements, not a character vector nor a scalar string (either of which is what you need). Remember that STRING arrays and CHAR arrays have very very very very very different syntaxes and behaviors when concatenating!
To get a scalar string use + on other strings (not concatenation like you tried):
"output "+string(datetime('now'))+".mat" % string scalar
OR to get a character vector use concatenation of other character vectors (but NO strings!):
['output ',char(datetime('now')),'.mat'] % char vector
But do not mix them up like you were doing!
Tip: if you are not sure what you need to use, then SPRINTF will always work for any input text (and will even coerce the DATETIME into text for you). Note that the output type is determined by the format type:
sprintf('%s', "output ", datetime('now'), ".mat") % char vector
sprintf("%s", "output ", datetime('now'), ".mat") % string scalar
"I wanted it in the 'yyyy-mm-dd_HH_MM_SS' format, but it's not that important."
Of course it is important, it is easy too by simply specifying the Format with DATETIME:
"output "+string(datetime('now','Format','yyyy-MM-dd_HH_mm_ss'))+".mat"
or exactly as you found in the STRING help:
"output "+string(datetime('now'),'yyyy-MM-dd_HH_mm_ss')+".mat"
More Answers (0)
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!