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

10 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

MathWorks Support Team
MathWorks Support Team il 28 Mar 2024
Modificato: MathWorks Support Team il 29 Mar 2024 alle 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

Più risposte (0)

Categorie

Scopri di più su Dates and Time in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by