WJA
WJA

Reputation: 7004

Quickest method to convert datenum to datetime in Matlab

I am having issue converting datenum to datetime in Matlab.

Given dnum = [floor(now); floor(now+1)];

I tried the following:

datenum(dnum)

But that did not work.

Ways that I found that work are:

datetime(datestr(dnum)) % seems slow?
datetime(year(dnum), month(dnum), day(dnum)) % slower?

What is the quickest way and are there better methods? Built-in functions?

Upvotes: 2

Views: 899

Answers (1)

WJA
WJA

Reputation: 7004

After experimenting with a couple of suggestions, this is the breakdown:

dnum = datenum(datetime(1900,1,1):datetime(2017,1,1))';

Then these are the results (Matlab 2016b):

% Elapsed time is 1.287081 seconds.
tic
dtime = datetime(datestr(dnum)); % seems slow?
toc

% Elapsed time is 0.017474 seconds.
tic
dtime = datetime(year(dnum), month(dnum), day(dnum));
toc

% Elapsed time is 0.010327 seconds.
tic
dtime = datetime(datevec(dnum));
toc

% Elapsed time is 0.000949 seconds.
tic
dtime = datetime(dnum,'ConvertFrom','datenum');
toc

Here is the function for copy/paste:

function dtime = datenum2datetime(dnum)
    dtime = datetime(dnum,'ConvertFrom','datenum');
end

Upvotes: 2

Related Questions