我有一个大小为1x8734的变量timestamp
。他们是最新的序列号,并说前3个元素是这样的:将日期序列号转换为实际日期
1.0e+05 *
7.3618 7.3620 7.3620
如果我使用datestr
,我可以得到正确格式的日期和时间。
我的问题是:我需要在我的代码中以循环形式使用这些日期和时间。第一个日期是Aug-04-2015 hh:mm:ss
。假设我需要在八月份选择所有的日期,那么我该怎么做呢?
我有一个大小为1x8734的变量timestamp
。他们是最新的序列号,并说前3个元素是这样的:将日期序列号转换为实际日期
1.0e+05 *
7.3618 7.3620 7.3620
如果我使用datestr
,我可以得到正确格式的日期和时间。
我的问题是:我需要在我的代码中以循环形式使用这些日期和时间。第一个日期是Aug-04-2015 hh:mm:ss
。假设我需要在八月份选择所有的日期,那么我该怎么做呢?
您可以使用timestamp
作为数字,只是比较一个预定义的日期,如下所示:
timestamp = randi(180,10,1)+1.0e+05 * 7.3609; % some arbitrary dates
starts = datenum('1-Aug-2015');
ends = datenum('31-Aug-2015');
for k = 1:numel(timestamp)
if timestamp(k)>=starts && timestamp(k)<=ends
% things to do...
disp(datestr(timestamp(k)))
end
end
而且你还可以去和矢量化这一点:
Aug_dates = timestamp>=starts & timestamp<=ends;
disp(datestr(timestamp(Aug_dates)))
因此,对于一组随机样日期:
11-Jul-2015
09-Jul-2015
18-May-2015
29-Oct-2015
23-Aug-2015
12-Oct-2015
20-Aug-2015
14-Oct-2015
16-Sep-2015
05-Oct-2015
你会在两种情况下得到的结果:
23-Aug-2015
20-Aug-2015
非常感谢。会尝试这个 – kanachi
这是可以做到用:
timestamp = 1.0e+05 * [ 7.3618 7.3620 7.3599 7.3620 ];
% I have included another value, i.e. 7.3599, for better understanding.
% 7.3599 is: 26-Jan-2015
abc = datestr(timestamp);
rowsabc = size(abc,1);
def = cell(rowsabc,1); %Pre-allocation
for k = 1:rowsabc %Using it in a loop as you said
def{k}= strfind(abc(k,:),'Aug'); % finding which dates include 'Aug'
end
required = abc(~cellfun('isempty', def),:); %removing the rows of abc not containing 'Aug'
或者,您可以使用避免循环:
timestamp = 1.0e+05 * [ 7.3618 7.3620 7.3599 7.3620 ];
abc = datestr(timestamp);
temp = abc.'; temp=temp(:).';
required = abc(ceil(strfind(temp,'Aug')./11),:);
均可以得到以下结果:
>> abc
abc =
04-Aug-2015
24-Aug-2015
26-Jan-2015
24-Aug-2015
>> required
required =
04-Aug-2015
24-Aug-2015
24-Aug-2015
非常感谢。会试试这个。 – kanachi
可以请你分享一下你得到这个时间戳矩阵的matlab代码吗? –