Convert datetime to datestr without losing milisecond data
Show older comments
I am calling in time and date data from an excel spreadsheet using the readcell function, with the resultant column consisting of datetime arrays (column 4). I tried to set the variable type as 'string' to solve the below problem, but it is still calling in collumn 4 as datetime.
opts = detectImportOptions(fname);
opts.Sheet = 2;
opts = setvartype(opts, 'string');
Data = readcell(fname,opts);
The problem I am having is that the original data called in has milliseconds included:
>> Data{1,4}
ans =
datetime
22-Jul-2023 15:18:15.171
But when I convert the datetime data into a string:
datestr(ans)
the result is
'22-Jul-2023 15:18:15'
losing the millisecond information.
Basically, I want to search the next line to see if the next datetime occurs within 2 seconds of the original (ie. if Data{2,4} is within 2.00 seconds of Data{1,4}) without losing the milisecond info.
So either is there a different way of converting the datetime to a string or char or anything that will not lose the millisecond information?
Or is there another way of calling in the spreadsheet data in the first place?
The data I want to call in from the spreadsheet is:
collumn 1: file names (includes numbers and letters)
collumn 2: participant name (letters)
collumn 4: datetime
collumn 7: data (numbers)
Thanks in advance!
Accepted Answer
More Answers (1)
"I tried to set the variable type as 'string' to solve the below problem"
The best way to import Excel serial date numbers is as DATETIME objects. Do not import as string.
"But when I convert the datetime data into a string: datestr(ans)"
Why are you using deprecated DATESTR?
"is there a different way of converting the datetime to a string or char or anything that will not lose the millisecond information?"
Of course, just use STRING or CHAR or SPRINTF or COMPOSE or anything else of that ilk:
dt = datetime('now','Format','yyyy-MM-dd HH:mm:ss.SSS')
char(dt)
string(dt)
sprintf("%s",dt)
"Or is there another way of calling in the spreadsheet data in the first place?"
READTABLE
Tip for the future: read the documentation of the functions you are using. When you open the DATESTR documentation this is at the very top, it already tells you the answer to your question:

2 Comments
Side Note: These methods work because of the Format. If you had a different Format they wouldn't. E.g.,
dt = datetime('now','Format','yyyy-MM-dd HH:mm:ss')
char(dt)
string(dt)
sprintf("%s",dt)
second(dt)
So, it is critical that you make sure the Format contains the fractional seconds you want before doing the conversion. They all missed the .5882 part above because those digits were not included in the Format.
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!