datetime 'InputFormat' syntax
이전 댓글 표시
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
Guillaume
2017년 10월 11일
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?
채택된 답변
추가 답변 (1개)
Steven Lord
2017년 10월 11일
0 개 추천
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
Emil Atz
2017년 10월 11일
Steven Lord
2017년 10월 11일
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.
카테고리
도움말 센터 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!