Readtable is not reading my delimiter and datetime columns correctly

47 ビュー (過去 30 日間)
Harrick Wu
Harrick Wu 2022 年 5 月 18 日
回答済み: Jeremy Hughes 2022 年 7 月 7 日
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.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by