我正在看一些非常难看的代码来完成以下工作:
function [ Y ] = timeStringToFloat( X )
% X is a column cell-array of time-strings, e.g.:
%
% 4215×1 cell array
%
% '5/1/2009 3:02:00 PM'
% '5/1/2009 4:11:00 PM'
% '5/1/2009' <-- if time missing, assume '12:00:00 AM'
% '6/1/2009 12:37:00 AM'
% '7/1/2009 3:08:00 AM'
% '7/1/2009 9:30:00 PM'
% etc.
%
%
% >> Y
%
% Y =
%
% 1.0e+05 *
%
% 7.337786263888889
% 7.337786743055555
% 7.337786826388889
% 7.337790256944444
% 7.337801305555556
% 7.337808958333333
% etc.
%
%
% Convert Entry Times to date numbers, but we have to ensure that all entries contain
% "HH:MM:SS PM" which is not the case for timestamps at 12:00:00 AM sharp.
% For cells containing "AM" or "PM" Replace [] with 0
IdxAM = strfind(X,'AM'); IdxAM(cellfun(@isempty,IdxAM)) = {0};
IdxPM = strfind(X,'PM'); IdxPM(cellfun(@isempty,IdxPM)) = {0};
% Entries without "HH:MM:SS PM" will be 0
IdxNoTime = cell2mat(IdxAM) + cell2mat(IdxPM);
if min(IdxNoTime) == 0 % There is at least one entry without "HH:MM:SS PM"
all_pos_without_time = find(IdxNoTime == 0);
for i = 1:sum(IdxNoTime == 0)
X{all_pos_without_time(i)} = [X{all_pos_without_time(i)},' 12:00:00 AM'];
end
end
Y = datenum(X,'dd/mm/yyyy HH:MM:SS PM');
% datestr(ENTRYTIMENUM,'dd/mm/yyyy HH:MM:SS PM'); % For checking
end有人能看到更漂亮的方法吗?
我正在考虑一些类似于X{ X[end]~='M' } += ' 12:00:00 AM';的东西,但我看不出用Matlab提供的语法来实现它的任何方法。
(速度在这里并不重要)。
发布于 2017-05-19 19:12:20
您可以首先使用datetime来用所需的格式'dd/MM/yyyy hh:mm:ss aa'转换所有日期,识别没有使用isnat转换的日期,然后用缩短的格式'dd/MM/yyyy'来转换那些日期。然后,可以使用datenum将其转换为数值。我使用函数帮助文本中的示例数据作为输入X。
% Input:
X = {'5/1/2009 3:02:00 PM'; ...
'5/1/2009 4:11:00 PM'; ...
'5/1/2009'; ...
'6/1/2009 12:37:00 AM'; ...
'7/1/2009 3:08:00 AM'; ...
'7/1/2009 9:30:00 PM'};
% Conversion code:
Y = datetime(X, 'Format', 'dd/MM/yyyy hh:mm:ss aa');
index = isnat(Y);
Y(index) = datetime(X(index), 'Format', 'dd/MM/yyy');
Y = datenum(Y);并确认正确的输出:
>> datestr(Y)
ans =
05-Jan-2009 15:02:00
05-Jan-2009 16:11:00
05-Jan-2009 00:00:00 % Notice it has assumed 12:00:00 AM
06-Jan-2009 00:37:00
07-Jan-2009 03:08:00
07-Jan-2009 21:30:00https://stackoverflow.com/questions/44077182
复制相似问题