readtable - Reading dates and times from text file
26 ビュー (過去 30 日間)
古いコメントを表示
I am struggling to use readtable to read data from a text file. The person supplying this file has changed it from a comma-delimited format to a tab-delimted format. I was using setvaropts and readtable to read the csv file, but I can't work out how to use them with this text file.
A typical file is attached. This is what the top of the file looks like:
Date Time Rain Rain (mm)
2022/07/07 11:17:01.0 0.00
2022/07/07 11:18:01.0 0.00
2022/07/07 11:19:01.0 0.00
2022/07/07 11:20:01.0 0.00
2022/07/07 11:21:01.0 0.00
And this is how readtable sees it:
Var1 Var2 Var3
______________ ________ ____
{'2022/07/07'} 11:17:01 0
{'2022/07/07'} 11:18:01 0
{'2022/07/07'} 11:19:01 0
{'2022/07/07'} 11:20:01 0
{'2022/07/07'} 11:21:01 0
How can I get these three variables into two, a datetime and a number?
0 件のコメント
採用された回答
その他の回答 (1 件)
dpb
2025 年 10 月 8 日 19:51
%type data.txt
opt=detectImportOptions('data.txt','ReadVariableNames',1,'VariableNamesLine',1)
tData=readtable('data.txt',opt);
opt.VariableTypes(1)={'datetime'};
opt=setvaropts(opt,'Date','InputFormat','yyyy/MM/dd');
tData=readtable('data.txt',opt);
tData.Date=tData.Date+tData.Time;
tData.Date.Format='default';
tData=removevars(tData,'Time');
head(tData)
They didn't do you any favors by having four variable labels for three variables and the extra space with the units will be a pain to use if keep that way.
The problem with the sample dataset is that 07/07 is ambiguous as to which is month and which is day; I made a choice above; you'll have to confirm if it is that or the other way 'round.
If you build the import options struct to match once the format is finalized, then you can save it and use it for all files of that type; you do not have to build one for every file.
It would be better if they would build the full date/time string as one instead of two and also pick an unambiguous output format for the date -- like the three-letter month, say.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Calendar についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!