Read in dates (for timestamp) from file names

10 次查看(过去 30 天)
I am trying to read in data and the measurement timestamps do not include the dates. The filenames include the date/time when the file was started. How can save the date from the filename to use it in the timestamps for each measurement?
I was previously doing this:
filepath = 'HR3_181920/PH/';
filelist = dir(strcat(filepath,'*.txt'));
file_timestamps =cell2mat({filelist.datenum});
But this doesn't work because it is taking the date from the structure for the datenum value which I think is actually the time when the file ends (not the beginning). I have attached a file of the resulting structure which includes the names of the files I am trying to work with.
These are the 'file_timestamps' that I currently get when I run those line. Notice they match the date column but not the information in the name of the file.
  2018 7 18 12 49 50
2018 7 18 12 54 48
2018 7 18 17 3 58
2018 7 19 0 0 2
2018 7 19 11 50 12
2018 7 19 11 54 18
2018 7 19 18 5 4
2018 7 19 18 25 20
2018 7 19 19 50 54
2018 7 19 20 26 12
2018 7 19 20 26 36
2018 7 19 20 27 20
2018 7 19 20 28 6
2018 7 19 20 28 54
2018 7 19 20 29 58
2018 7 19 20 32 28

采纳的回答

dpb
dpb 2019-3-26
编辑:dpb 2019-3-26
Just parse the filename itself...
fmt='yyyyMMMdd_HH-mm-ss';
tstr=cellstr(strvcat(d.name));
file_timestamps=cellfun(@(x) datetime(x(1:18),'InputFormat',fmt),tstr);
or just do each inside the loop and can do without the conversion to cellstr array and cellfun to just parse each substring.
ERRATUM: I had a t test array; thought better variable name wise but didn't fixup the second reference to match...
...
file_timestamp=datetime(d(i).name(1:18),'InputFormat',fmt);
...

更多回答(1 个)

Walter Roberson
Walter Roberson 2019-3-26
file_timestamps = datetime( regexp({filelist.name}, '^[^_]*', 'match', 'once'), 'InputFormat', 'yyyyMMMdd');

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by