user3353703
user3353703

Reputation: 13

avoiding a for loop to convert date/time string to number

I am looking for some expression that would help me avoiding to do a for loop as I have more than 2000000 lines. So first, I need to get date and time which are in string ('yyyy-mm-dd') and ('dd:mm:ss') to a timevec or time number;

I have started the following;

n=length(TEMP);
for i5=1:n
date_tmp(i5,:)=sscanf(TEMP.Date(1,:),'%4d-%2d-%2d');
time_tmp(i5,:)=sscanf(TEMP.Time(1,:),'%2d:%2d:%2d');
datetime_tmp(i5,:)=[date_tmp(i5,:),time_tmp(i5,:)];
i5
end

Obviously this should be written much better, Any help welcome, Thanks

Upvotes: 0

Views: 73

Answers (1)

MrAzzaman
MrAzzaman

Reputation: 4768

You can use datevec, no need to loop over anything:

datevec(["2016-06-02 01:04:02","2016-06-02 01:04:01"])
ans =
    2016           6           2           1           4           2
    2016           6           2           1           4           1

EDIT: As Hoki pointed out, you can just as easily do this with datenum (or indeed with datetime), if you would prefer a datenum or datetime object. The syntax is exactly the same, just replace datevec with either datenum or datetime.

Upvotes: 2

Related Questions