Use "find" function in "datetime"

60 次查看(过去 30 天)
I have some entries as datetime class. I am trying to get the id where the entry for date is "2016-02-18 00:00:00" for instance. I know I have the exact point there but the id is empty. It works for some other columns of datetime but for one of them does not work!
id=find(time=='2016-02-18 00:00:00')
id = 0×1 empty double column vector
I appreciate any help.

采纳的回答

Walter Roberson
Walter Roberson 2023-10-18
T = [datetime(2016,2,18); datetime(2016, 2, 18, 0, 0, 0.1)]
T = 2×1 datetime array
18-Feb-2016 00:00:00 18-Feb-2016 00:00:00
id = find(T == '2016-02-18 00:00:00')
id = 1
Both entries display the same with the default format, but that does not mean they are equal.
T.Format = 'dd-MMM-yyyy HH:mm:ss.SSSSSS'
T = 2×1 datetime array
18-Feb-2016 00:00:00.000000 18-Feb-2016 00:00:00.100000
T2 = dateshift(T, 'start', 'second')
T2 = 2×1 datetime array
18-Feb-2016 00:00:00.000000 18-Feb-2016 00:00:00.000000
id2 = find(T2 == '2016-02-18 00:00:00')
id2 = 2×1
1 2

更多回答(1 个)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2023-10-18
It looks like your imported data variable name may not be correctly assigned. Here is a plain example where datetime works ok:
%% Set up the Import Options and import the data
opts = delimitedTextImportOptions("NumVariables", 2);
% Specify range and delimiter
opts.DataLines = [2, Inf];
opts.Delimiter = " ";
% Specify column Names and Types
opts.VariableNames = ["Time", "Data"];
opts.VariableTypes = ["datetime", "double"];
% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";
opts.ConsecutiveDelimitersRule = "join";
opts.LeadingDelimitersRule = "ignore";
% Specify variable properties
opts = setvaropts(opts, "Time", "InputFormat", "yyyy-MM-dd HH:mm:ss");
% Import the data
D = readtable("DATE_Data.txt", opts); % Note that the imported data is a table variable
IDX=find(D.Time=='2016-02-18 00:00:00')
IDX = 2×1
1 4
% Check
D(IDX,:)
ans = 2×2 table
Time Data ___________ _____ 18-Feb-2016 13 18-Feb-2016 23.23

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by