Generating array of consecutive timestamps in double
이전 댓글 표시
I need to generate an array of consecutive timestamps, in double and yyyymmddHHMMSS format, for specified start and end times. For example:
timestamps(1) = 2.012082104000000e+013;
timestamps(2) = 2.012082104000100e+013;
...
...
timestamps(120) = 2.012082104020000e+013;
I wrote a working piece of code, but the str2double/datestr combination in the parfor loop is too slow (I used 120 seconds as an example, but in actual use, I will be generating about 10^7 consecutive seconds of timestamps). Is there a faster way to do this?
if matlabpool('size') == 0
matlabpool local
end
startDate = num2str(2.012082104000000e+013);
endDate = num2str(2.012082104020000e+013);
startDateyyyy = str2double(startDate(:,1:4));
startDatemm = str2double(startDate(:,5:6));
startDatedd = str2double(startDate(:,7:8));
startDateHH = str2double(startDate(:,9:10));
startDateMM = str2double(startDate(:,11:12));
startDateSS = str2double(startDate(:,13:14));
startDateVec = [startDateyyyy startDatemm startDatedd startDateHH ...
startDateMM startDateSS];
startDate = datenum(startDateVec);
endDateyyyy = str2double(endDate(:,1:4));
endDatemm = str2double(endDate(:,5:6));
endDatedd = str2double(endDate(:,7:8));
endDateHH = str2double(endDate(:,9:10));
endDateMM = str2double(endDate(:,11:12));
endDateSS = str2double(endDate(:,13:14));
endDateVec = [endDateyyyy endDatemm endDatedd endDateHH ...
endDateMM endDateSS];
endDate = datenum(endDateVec);
timestamps = startDate:(1/24*1/60*1/60):endDate;
parfor i = 1:length(timestamps)
timestamps(i) = str2double(...
datestr(timestamps(i),'yyyymmddHHMMSS'));
end
Thanks in advance!
댓글 수: 3
Oleg Komarov
2012년 9월 11일
Why not serial dates as generated by datenum()?
Oleg Komarov
2012년 9월 11일
As you can see from my answer, the appearance of dates can be controlled with datestr() and I still recommend to store dates as MATLAB serial numbers produced with datenum(). I am posting an alternative solution to let you see how bothersome is to store dates in a different way.
채택된 답변
추가 답변 (1개)
Amarjit Dhillon
2017년 8월 31일
Let's say we want to generate timestamps in the format of yyyymmddHHMMSS for 10 days
1-Jan-2017 at 12:00:00 to 10-Jan-2017 till 12:00:00, This can be easily generated by below-written code
t1 = datetime(2017,1,1,12,0,0);
t2 = datetime(2017,1,10,12,0,0);
data = t1:seconds(1):t2;
datestr(data,'yyyymmddHHMMSS')
댓글 수: 1
Peter Perkins
2017년 8월 31일
Amarjit, your suggestion to use datetime is a good one (the OP was from 1012, before datetime existed in MATLAB). But actually, there's usually no reason to convert it to text. Just change the format:
>> data.Format = 'yyyymmddHHMMSS'
data =
1×3 datetime array
20170001120100 20170001120100 20170001120100 ...
카테고리
도움말 센터 및 File Exchange에서 Time Series Objects에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!