How do I convert arrays of dates containing multiple formats to "datetime" in MATLAB R2022a?

조회 수: 18 (최근 30일)
I am converting an array of strings containing dates to type "datetime" in MATLAB R2022a, however, there are two variations of formats within my input. The inputs follow one of the following formats:
1) "yyyy-MM-dd HH:mm:ss.SSS"
2) "yyyy-MM-dd HH:mm:ss"
When I call the "datetime" function on my input, I get many NaT values in my output. The call only seems to convert one of the previously listed types and all "DateStrings" of the other format return as NaT. The following code demonstrates the issue:
>> dateStrings = ["2024-03-04 14:27:12.1"; "2024-03-04 14:27:12"; "2024-03-04 14:27:12.001"];
>> dt = datetime(dateStrings,"Format", "yyyy-MM-dd HH:mm:ss.SSS")
dt = 3×1 datetime array
       2024-03-04 14:27:12.100
       NaT
       2024-03-04 14:27:12.001
As the code shows, "datetime" does not recognize the second element as a time since it is in a different format. What steps can I take to avoid this issue?

채택된 답변

MathWorks Support Team
MathWorks Support Team 2024년 3월 28일
편집: MathWorks Support Team 2024년 3월 29일 13:55
You can work around this by converting all the date strings using the format appropriate for the first date string. Then, you can detect any entries that "datetime" did not recognize by using the "isnat" function to check for NaT values in the result. If "dt" is the result after converting the string array to a datetime array, you can execute this code to detect NaT values:
>> natlocations = isnat(dt)
natlocations = 3×1 logical array
                       0
                       1
                       0
For more information about "isnat", see its documentation:
https://www.mathworks.com/help/releases/R2022a/matlab/ref/datetime.isnat.html
If the array contains any NaT values, use indexing to select the corresponding date strings, convert those using the other format(s), and assign them to the NaT elements in the array.
>> if any(natlocations)
dt(natlocations) = datetime(dateStrings(natlocations), "Format", "yyyy-MM-dd HH:mm:ss")
>> end
dt = 3×1 datetime array
       2024-03-04 14:27:12.100
       2024-03-04 14:27:12.000
       2024-03-04 14:27:12.001

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by