MATLAB Answers

0

How to account for the day suffix when using datetime to recognise dates in matlab?

Pedro Viana さんによって質問されました 2019 年 11 月 1 日
最新アクティビティ Pedro Viana さんによって コメントされました 2019 年 11 月 5 日
I have a cell array T containing a column of dates from several events, formatted as follows:
17×1 cell array
{'Mon 14th Oct 2019 8:23:48 am' }
{'Thu 10th Oct 2019 8:00:26 am' }
...
{'Tue 3rd Sep 2019 9:03:53 am' }
{'Thu 22nd Aug 2019 6:00:29 am' }
I would like to use datetime to recognize the dates in each cell, however the date contains the suffix for the day of the month ("14th", "10th", etc.), and I couldn't find an option in the input format to account for day suffixes.
If I (manually) remove the suffixes from the days, the following works fine:
datetime(T{1,1},'InputFormat','eeee dd MMMM yyyy hh:mm:ss a')
ans =
datetime
14-Oct-2019 08:23:48
Is there a way to account for the day suffixes (or to automatically remove them before using datetime)?
Thanks
Pedro Viana

  0 件のコメント

サインイン to comment.

製品


リリース

R2019b

2 件の回答

回答者: Peter Perkins
2019 年 11 月 4 日
 採用された回答

Pedro, you could put a literal th in the format,
'eeee dd ''th''MMMM yyyy hh:mm:ss a'
and read most of them, and go back and read all the places where you got a NaT, using a literal nd in the format, then again with a literal st. But honestly, the simplest thing is to use replace or strrep to pre-process the text.
Just out of curiosity, where did these timestamps come from?

  1 件のコメント

Pedro Viana 2019 年 11 月 5 日
Thank you for your help. I ended up writing a looped script to remove the 2-letter suffix after the first number that appears on the string (independently of whether it's "th", "st", "nd", "rd").
for i = 1: size(T,1)
B = regexp(T{i,1},'\d*','Match'); % extract numbers in the string
U = char(T{i,1}); % change to char format
% concatenate the string from beginning up to number, then from space until
% the end
T{i,1}{:} = [U(1:4+size(B{1}{1},2)) U(5+size(B{1}{1},2)+2:end)];
end
These are entries from an eDiary app.
Thank you

サインイン to comment.


回答者: Jyotsna Talluri 2019 年 11 月 5 日

If dates are in a particular format given by you,suffixes {"th","nd","st","rd"} can be removed by
erase(T,["th","nd","st","rd"]);
There can be other ways to do this also

  0 件のコメント

サインイン to comment.



Translated by