Rearranging dates to make them suitable for datetime format

조회 수: 3 (최근 30일)
AA
AA 2020년 8월 25일
편집: Steven Lord 2020년 8월 25일
Hi,
I have a cell array with many dates that were imported from an excel file.
Each cell array entry has differnt inputs ie 08/21/2020 (Aug), 05/26/2018 (May), 04/03/2016, 02/06/2005 (QQ).
I just neee the dates and then import them as datetime format. How can I cut the brackets out so that I can import the file into a datetime format. Remember that some of the dates above dont have brackets.
Thanks

채택된 답변

Stephen23
Stephen23 2020년 8월 25일
>> C = {'08/21/2020 (Aug)';'05/26/2018 (May)';'04/03/2016';'02/06/2005 (QQ)'};
>> D = datetime(regexp(C,'^.{10}','match','once'),'InputFormat','MM/dd/yyyy')
D =
21-Aug-2020
26-May-2018
03-Apr-2016
06-Feb-2005

추가 답변 (1개)

Steven Lord
Steven Lord 2020년 8월 25일
편집: Steven Lord 2020년 8월 25일
If you need to import data in multiple formats, start by trying to import all the data in one of the formats. The entries that cannot be interpreted in that format will be NaT in the resulting datetime array. Fill in those NaT entries using logical indexing.
>> C = {'08/21/2020 (Aug)';'05/26/2018 (May)';'04/03/2016';'02/06/2005 (QQ)'}
C =
4×1 cell array
{'08/21/2020 (Aug)'}
{'05/26/2018 (May)'}
{'04/03/2016' }
{'02/06/2005 (QQ)' }
>> dt = datetime(C, 'InputFormat', 'MM/dd/yyyy')
dt =
4×1 datetime array
NaT
NaT
03-Apr-2016
NaT
>> dt(isnat(dt)) = datetime(C(isnat(dt)), 'InputFormat', 'MM/dd/yyyy (MMM)')
dt =
4×1 datetime array
21-Aug-2020
26-May-2018
03-Apr-2016
NaT
Repeat until there are no more NaT values in the datetime array and/or no more potential input formats to try.

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by