I have this code to help format a list of dates/times in a CSV file:
datfmt = '%s%s%s%s%f%s%s%s%d%s%f%s';
celldata = textscan(fid,datfmt,'Headerlines',1,'Delimiter',',');
dates = datetime(celldata{3});
When I try to write an output file using:
for iline = 1:length(dates)
fprintf(fid,'%s\n',dates(iline));
end
the dates/times at the 0:00 mark don't read out with both the dates/times, only the dates (formatted differently than all the other values too). Why is this happening?

 채택된 답변

Walter Roberson
Walter Roberson 2023년 6월 9일

2 개 추천

datetime('01/31/1983'), ans.Format
ans = datetime
31-Jan-1983
ans = 'dd-MMM-uuuu'
datetime('01/31/1983 00:00'), ans.Format
ans = datetime
31-Jan-1983
ans = 'dd-MMM-uuuu'
datetime('01/31/1983 17:45'), ans.Format
ans = datetime
31-Jan-1983 17:45:00
ans = 'dd-MMM-uuuu HH:mm:ss'
What is happening is that when you do not supply a Format, the default format for time 00:00 is just the date without the time. If you want the time as well, specify a format specifically
datetime('01/31/1983 00:00', 'Format', 'dd-MMM-uuuu HH:mm:ss'), ans.Format
ans = datetime
31-Jan-1983 00:00:00
ans = 'dd-MMM-uuuu HH:mm:ss'

댓글 수: 1

Peter Perkins
Peter Perkins 2023년 7월 17일
Walter is right, but even MORE right would be to say, "CSV? use readtable, and tell it to read those timestamps directly into a datetime variable." textscan is not your friend.

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

추가 답변 (1개)

the cyclist
the cyclist 2023년 6월 9일

2 개 추천

It's not easy to debug this without seeing the data, but I would suggest explicitly adding a 'Format' Name-Value input to this line
dates = datetime(celldata{3});
so that that those dates are forced to include the time.

카테고리

도움말 센터File Exchange에서 Software Development에 대해 자세히 알아보기

제품

릴리스

R2022b

질문:

2023년 6월 9일

댓글:

2023년 7월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by