Problem with formatting operators - textscan

3 ビュー (過去 30 日間)
JSL
JSL 2013 年 9 月 25 日
編集済み: Stephen23 2025 年 4 月 8 日
I'm trying to bring in some data from a .csv file, but I can't seem to get the formatting operators correct when using textscan(). I'm sure this problem is trivial for someone with more experience. My data is all on one line separated by commas. Format:
XX mins YYYY-MM-DD hh:mm:ss, XX mins YYYY-MM-DD hh:mm:ss, XX mins YYYY-MM-DD hh:mm:ss,
Example data:
26 mins 2013-09-17 09:01:45, 29 mins 2013-09-18 16:53:12, 33 mins 2013-09-19 18:24:27,
After using fopen to open the file, I am trying to use textscan:
f = fopen('data.csv');
c = textscan(f,????,'Delimiter',',');
I've tried experimenting with different formatting operators at ????, but can't get anything that makes sense. I would like to extract the following as integers:
XX, YYYY, MM, DD, hh, mm, ss
Help?

回答 (1 件)

Stephen23
Stephen23 2025 年 4 月 8 日
編集済み: Stephen23 2025 年 4 月 8 日
txt = '26 mins 2013-09-17 09:01:45, 29 mins 2013-09-18 16:53:12, 33 mins 2013-09-19 18:24:27,';
Directly obtaining the integers you requested:
tmp = textscan(txt,'%f %*[^ ]%f%f%f%f%f%f', 'EndOfLine',',', 'Delimiter',{'-',':'}, 'CollectOutput',true)
tmp = 1x1 cell array
{3x7 double}
tmp{1}
ans = 3×7
26 2013 9 17 9 1 45 29 2013 9 18 16 53 12 33 2013 9 19 18 24 27
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Or an alternative solution using DATETIME for the timestamp:
tmp = textscan(txt,'%f%*s%D%T', 'EndOfLine',',')
tmp = 1x3 cell array
{3x1 double} {3x1 datetime} {3x1 duration}
vec = tmp{1}
vec = 3×1
26 29 33
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
dt = tmp{2}+tmp{3};
dt.Format = 'yyyy-MM-dd HH:mm:ss'
dt = 3x1 datetime array
2013-09-17 09:01:45 2013-09-18 16:53:12 2013-09-19 18:24:27
dt.Year
ans = 3×1
2013 2013 2013
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
dt.Month
ans = 3×1
9 9 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
% etc...
dt.Second
ans = 3×1
45 12 27
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by