Error reading dates when using readtable function

조회 수: 1 (최근 30일)
Ben Whitby
Ben Whitby 2022년 12월 13일
댓글: Ben Whitby 2022년 12월 13일
Hi Guys,
I have some date time values in an Excel (xlsx file). The date times are in a custom format( dd/mm/yyyy hh:mm:ss) as shown below:
01/10/2021 00:00:00
01/10/2021 00:05:00
01/10/2021 00:10:00
01/10/2021 00:15:00
01/10/2021 00:20:00
01/10/2021 00:25:00
01/10/2021 00:30:00
01/10/2021 00:35:00
01/10/2021 00:40:00
01/10/2021 00:45:00
01/10/2021 00:50:00
01/10/2021 00:55:00
01/10/2021 01:00:00
I use the readtable function as follows to get the data from Excel into Matlab:
fileList = dir('*.xlsx');
DATA = [];
for i=2 %numel(fileList)nn
data = readtable([fileList(i).folder '\' fileList(i).name]);
DATA = [DATA; data];
end
For some reason after reading in the data Matlab changes the times by 1 second. For example it changes 01/10/2021 00:15:00 to
01/10/2021 00:14:59 as shown below:
However it doesn't do it for the first three readings. Any idea why this happens???

채택된 답변

Walter Roberson
Walter Roberson 2022년 12월 13일
N = dateshift(datetime('now'), 'start', 'minute')
N = datetime
13-Dec-2022 04:55:00
N
N = datetime
13-Dec-2022 04:55:00
N - seconds(eps(0))
ans = datetime
13-Dec-2022 04:54:59
You can see that for display purposes, MATLAB does not round up if even the smallest possible amount is subtracted from the time.
If I recall correctly, Excel custom date formats round.
I think if you were to look at the underlying time representations in the xls file, you would find that it is not exactly the full seconds you expect.
  댓글 수: 2
Peter Perkins
Peter Perkins 2022년 12월 13일
Walter is on the right track. Excel represents dates/times as whole+fractional number of days, so essentially every timestamp involves round-off. datetime tries to account for that, but doesn't always succeed. A lot depends on what's actually in the xlsx and what the cells are formatted as (text, numeric, datetime). The values in the xlsx may well be off by enough to foil what datetime does. Can't say without a file.
You can always use dateshift to round, but that seems unfortunate. And if you read them as text and convert, round-off doesn't enter in.
Ben Whitby
Ben Whitby 2022년 12월 13일
Thanks, I found that when saving the excel file as a .csv and reading in from that file it solves the problem.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by