How do I convert arrays of dates containing multiple formats to "datetime" in MATLAB R2022a?
조회 수: 18 (최근 30일)
이전 댓글 표시
MathWorks Support Team
2024년 3월 27일
편집: MathWorks Support Team
2024년 3월 29일 13:55
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
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Dates and Time에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!