Dates and Times Refuse to Concatenate Into One Column
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello, I have a csv file with dates and times in the following format:
dd-mm-yyyy hh-mm-ss-SSS
20-09-2022 22:16:39.163
I've tried date string and datenum, and have had a friend try as well. No matter what we try, the dates and times refuse to combine into one large date - time value. Any help would be greatly appreciated
Additional Data:
running MATLAB version R2022b - academic use
Example CSV is attached
댓글 수: 3
Les Beckham
2023년 2월 17일
What version of Matlab are you using? Please provide a sample csv file -- edit your question and attach it using the paperclip icon.
채택된 답변
Walter Roberson
2023년 2월 17일
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/1299205/example%20csv%20data.txt';
datecols = [1 9 14 19 27 32 37 45 50 55 63 68];
opts = detectImportOptions(filename, 'VariableNamingRule', 'preserve', 'HeaderLines', 1);
opts = setvartype(opts, datecols, 'datetime');
opts = setvaropts(opts, datecols, 'InputFormat', 'dd-MM-uuuu', 'DateTimeFormat', 'dd-MM-uuuu HH:mm:ss.sss');
T = readtable(filename, opts);
T{:,datecols} = T{:,datecols} + T{:,datecols+1};
T = removevars(T, datecols+1); %time merged into date
T(1:5,:)
추가 답변 (1개)
Cris LaPierre
2023년 2월 17일
I found that using the import tool did not correctly autodetect the Date and Time fomats correctly.
The approach I would use is to read in the date as a datetime, and the time as a duration, and then add the two together. I don't see duration as a datetype option in the import tool, so I would opt to use readtable and set the import options manually.
opts = detectImportOptions("example csv data.txt");
% Capture the variable names from the file
opts.VariableNamesLine = 2;
% Identify columns with Dates and Times
dCols = [1,9,14,19,27,32,37,45,50,55,63,68];
tCols = [2,10,15,20,28,33,38,46,51,56,64,69];
% Set date import and display options
opts = setvartype(opts,dCols,'datetime');
opts = setvaropts(opts,dCols,"InputFormat","dd-MM-yyyy","DatetimeFormat","dd/MM/yyyy HH:mm:ss.SSS");
% Set time import optoins
opts = setvartype(opts,tCols,'duration');
opts = setvaropts(opts,tCols,'InputFormat',"hh:mm:ss.SSS");
% Import table
F = readtable("example csv data.txt",opts);
% Combine date and time data
F{:,dCols} = F{:,dCols}+F{:,tCols};
% Delete time data, as it is redundant
F(:,tCols) = [];
% Change Date variable names to now say 'Datetime'
F.Properties.VariableNames = replace(F.Properties.VariableNames,"Date","Datetime")
Just a caution that this is quick and dirty. I have not extensively checked the results to ensure they are correct.
댓글 수: 1
Cris LaPierre
2023년 2월 17일
Nice to see Walter and I have similar solutions :) This is largely redundant, but I'll leave it for now.
참고 항목
카테고리
Help Center 및 File Exchange에서 Calendar에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!