Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

date - Convert dd.MM.yyyy HH:mm:ss to seconds using MATLAB

I work with csv and must subtract 2 cells with the following date format dd.MM.yyyy HH:mm:ss. I need to extract only the seconds.

Timestamp is a column and I attempted:

data1 = Timestamp(1) ;
data2 =  Timstamp(2) ; % returns error
class(data1); % returns cell 
data1 - data2 % returns error

How can I convert the cells into a number which I can subtract?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can index into your cell to extract the date string. Then you can use datenum to convert it to "decimal days since 1st January 0000". Then it's a simple matter of subtracting your starting date (convert that using datenum as well) and changing from decimal days to seconds:

tmp = your_cell{1}; % e.g. 26.11.2020 00:00:00, is a string
tmp_date = datenum(tmp); % MATLAB datenum, decimal days.
tmp_date2 = datenum(your_cell{2});
no_start = tmp_date2-tmp_date;  % remove starting date
time_sec = no_start*(24*60*60);  % change decimal days to seconds

Or as a oneliner:

(datenum(your_cell{2})-datenum(your_cell{1}))*(24*60*60)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...