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!