可能是一个愚蠢的问题,但在matlab中我导入了CSV数据。我导入工作区的其中一列是时间戳,格式为“4568x1 cell”(存储为字符串)。它的格式为
timestamp(1) = 'Reading time"
timestamp(2) = '2014-12-19 00:00:43 UTC'
timestamp(3) = '2014-12-19 00:01:43 UTC'
,等我如何得到小时,所以我得到00,01等,并将其存储在一个新的数组?
答案 0 :(得分:2)
您需要使用datenum
将日期字符串转换为数字格式,例如
timestamp{2} = '2014-12-19 00:00:43 UTC'; % use curly braces as cell array
timestamp{3} = '2014-12-19 00:01:43 UTC';
date_num(1) = datenum(timestamp{2}(1:end-4),'yyyy-mm-dd HH:MM:SS'); % remove the ' UTC' characters at the end of the string
date_num(2) = datenum(timestamp{3}(1:end-4),'yyyy-mm-dd HH:MM:SS'); % remove the ' UTC' characters at the end of the string
% etc... (use a for loop to go through all elements of the cell array)
hh = [0 diff(date_num)*24*60]; % elapsed time in hours, taking the first time stamp as reference
答案 1 :(得分:2)
由于小时由:
符号包围的数字组成,您可以轻松地将regular expression与lookaround一起应用,然后将检测到的字符串转换为数字:
%// Data
timestamp{1} = 'Reading time';
timestamp{2} = '2014-12-19 00:00:43 UTC';
timestamp{3} = '2014-12-19 00:01:43 UTC';
%// Get hours as a cell array of cells containing strings:
hours_cells = regexp(timestamp(2:end), '(?<=:)(\d+)(?=:)', 'match'); %// no title
%// Convert to numbers:
hours = cellfun(@(x) str2num(x{1}), hours_cells);
如果字符结构已修复(每个数字包括左零填充以均衡宽度),您可以识别小时的位置(在这种情况下为字符15和16)并更简单地执行:
hours = cellfun(@(x) str2num(x([15 16])), timestamp(2:end));
或者,可能更快,
hours = cellfun(@(x) (x([15 16])-48)*[10;1], timestamp(2:end));
%// 48 is ASCII for '0'
答案 2 :(得分:2)
我只是在修剪后使用datevec
:
timestamp(1) = []; % remove the first line
timestamp = cell2mat(timestamp); % now all are same length can do this
timestamp = timestamp(:,1:end-4); % remove UTC part
timevec = datevec(timestamp); % probably don't need format specifier
time_date
现在应该是4567 x 6矩阵(因为我们删除了一行),其中列是年,月,日,小时,分钟和秒。因此,我们只需要这个时间:
hours = time_date(:,4);