Readtable is not reading my delimiter and datetime columns correctly

조회 수: 50(최근 30일)
I'm trying to read in a csv file with
d = readtable('testCheck.csv');
but Matlab isn't detecting the delimiter correctly. It detects the delimiter as ' ', instead of ','. I then tried the command.
d = readtable('testCheck.csv','Delimiter', ',');
This command formats the file correctly, besides the 5th and 6th column,which are datetimes. It is reading them as strings, but I want them read as datetimes instead. I tried converting those two columns to datetimes, but I'm having trouble because the times include AM and PM.
Is there a way to read in the file with the times read in as datetime or a way to convert the strings of time with AM/PM to a 24 hour format instead?
  댓글 수: 1
Jeremy Hughes
Jeremy Hughes 2022년 7월 7일
It would be easier to help if you include an example file. I'll add an answer that should get close.

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

답변(2개)

Steven Lord
Steven Lord 2022년 5월 18일
You might want to use the interactive Import Tool to read in your data. This will let you select how the data is delimited / separated, choose which columns get read in, and specify the types and (where appropriate) formats of the data.
If you need to import multiple files with the same format, you can also perform the setup steps manually then generate code that you can run to import the remainder of the files automatically. You can also study the generated code to learn more about the commands and options MATLAB used to import the data.

Jeremy Hughes
Jeremy Hughes 2022년 7월 7일
Passing in the delimiter is the right thing to do. The detectImportOptions function (which is being called by readtable) tries to pick the delimiter based on the contents of the file, and sometimes that doesn't give you what you might expect. For example:
opts = detectImportOptions(filename,'Delimiter',',')
will do better than calling it without the delimiter.
from that, you can set the types, and the format for the dates:
opts = setvaropts(opts,[5 6],'Type','Datetime','DatetimeFormat','MM/dd/uuuu hh:mm:ss a')
Hope this helps get you closer to your goal.

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by