datetime 'InputFormat' syntax
Mostrar comentarios más antiguos
I am looking to convert a cell array of dates to a datetime array. From the text file BUContactOutput.txt I need the Start Time and Stop time in separate datetime arrays. This section of code shows how I am going about creating the StartTime datetime array.
ContactData = readtable('BUContactOutput.txt',...
'Delimiter', ' ', 'HeaderLines',4);
NumOfContacts = height(ContactData);
StartTime = cell(NumOfContacts,1);
for i = 1:NumOfContacts
day = num2str(ContactData.Var1(i));
month = char(ContactData.Var2(i));
year = num2str(ContactData.Var3(i));
time = char(ContactData.Var4(i));
StartTime{i,1} = strcat(year,'-',month,'-',day,'-',time);
end
datetime(StartContact, 'InputFormat', 'yyyy-MMM-dd-HH:mm:SSS')
This method is successful when the time component of StartTime is not included (no ,'-',time in the strcat function and no -HH:mm:SSS in datetime function), yet is not successful when the time component is included. I believe I have a syntax error in my 'InputFormat' content. I am unsure how to resolve the issue and the documentation has yet to provide me with a solution.
https://www.mathworks.com/help/matlab/ref/datetime.html#
Thanks ahead to anyone who offers help.
-Emil
1 comentario
Guillaume
el 11 de Oct. de 2017
A few questions
- is StartContact the same as StartTime?
- why are you converting days, months, etc. to strings to parse them back into number in the datetime?
- Why the loop?
- What is the actual content of time and month?
Respuesta aceptada
Más respuestas (1)
Steven Lord
el 11 de Oct. de 2017
0 votos
I suggest using the Import Tool. Using this you can experiment with datetime formats and column widths then import the data to a variable, generate a script file, and/or generate a function file. The latter two options allow you to use the results of your experimentation to automatically import other data files with the same format in the future or to tweak the import process.
For your file, I removed the delimiters separating each of the components of your start and stop times from the default (which were set by using spaces as the delimeter.) I changed the first two columns to import as datetime arrays using the custom format dd MMM yyyy HH:mm:ss.SSS. Hovering over one of the elements in columns A and B showed me that each would import correctly. I then selected to read column C as a number and imported it and the results were what I expected.
2 comentarios
Emil Atz
el 11 de Oct. de 2017
Steven Lord
el 11 de Oct. de 2017
Use the Import Tool once to generate a function file that imports the first data file.
Run the generated function file to import the second, third, fourth, etc. data files.
Categorías
Más información sobre Dates and Time en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!