How to convert excel date and time data into numerical integer matrix [year, month, day, hour, minute, second]
조회 수: 9 (최근 30일)
이전 댓글 표시
Greetings,
I have huge excel data starts with the following columns:
Sample data file attached.
I want to sort the data by comparing months/years/hours inside functions. Hence, I need the years, months, days, hours to be seperate integers.
needed output:
year = 2016
month = 11
day = 23
hour = 16
minute = 33
How can I do that (knowing I have tried reading file as table and time table and many other functions).
I would apreciate any help.
댓글 수: 2
Stephen23
2022년 11월 21일
@Anwaar Alghamdi: please upload a sample file by clicking the paperclip button. This does not have to be your complete data file or contain your confidential data, but it does need to exactly represent the format of your actual data files.
채택된 답변
Stephen23
2022년 11월 21일
fnm = 'sample data.xlsx';
obj = detectImportOptions(fnm);
obj = setvartype(obj,'date','datetime');
obj = setvartype(obj,'time','duration');
tbl = readtable(fnm,obj)
DT = tbl.date + tbl.time
[Year,Mon,Day] = ymd(DT)
[Hour,Min,Sec] = hms(DT)
댓글 수: 3
Stephen23
2022년 11월 22일
"How can I assign the other columns (numerical values) to variables?"
vec = tbl.value
Stephen23
2022년 11월 24일
편집: Stephen23
2022년 11월 24일
"...how can I convert the matrix [year month day hour] back to the same date and time excel columns, with all zero minutes?"
What matrix? Why not just work with the DATETIME/DURATION obejcts?
In any case, given such an Nx4 matrix (note an Nx6 matrix would be simpler to work with):
mat = [2022,11,24,6; 2022,11,24,14; 1973,12,31,23]
dtm = datetime(mat(:,1),mat(:,2),mat(:,3),mat(:,4),0,0)
tbl = table(dtm)
writetable(tbl,'myfile.xlsx')
추가 답변 (1개)
cr
2022년 11월 21일
An easier way of doing that would be convert the dates into datenum so that you dont have to individually compare years,months,...sec,millisec. date_number = datenum(datescolumn);
Unless you are using older versions of Matlab, a column with dates is automatically imported as datenumbers. If it doesn't datenum() may be used.
댓글 수: 2
cr
2022년 11월 21일
Well, then you may create your own date number for dates based on years, days and hours. To seggregate the dates into these use datavec(). E.g.
ymd = datevec(datesColumn);
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!