datetime sometimes returns NaT and sometimes throws an error – what is the expected behaviour?

Sometimes datetime throws an error if it can’t return a valid datetime object from a string input:
dt = datetime(["2026_06" "2026_06_13"], Format = "yyyy_MM_dd")
and sometimes it returns NaT:
dt = datetime(["2026_06_13" "2026_06"], Format = "yyyy_MM_dd")
dt =
1×2 datetime array
2026_06_13 NaT
The second result is what I’d expect from the documentation. I’m having difficulty figuring out what the underlying rule is, since the two examples have the same input apart from the order and the same format. It seems to be to do with whether the first element of the array can be interpreted according to the format.
It looks like I have to put every call to datetime in a try-catch block and also test the result result for NaT, if I’m to detect any non-conforming input. This seems excessive – can anyone suggest a better way, or whether this is actually a bug I should try to report?Sometimes datetime throws an error if it can’t return a valid datetime object from a string input:
dt = datetime(["2026_06" "2026_06_13"], Format = "yyyy_MM_dd")
and sometimes it returns NaT:
dt = datetime(["2026_06_13" "2026_06"], Format = "yyyy_MM_dd")
dt =
1×2 datetime array
2026_06_13 NaT
The second result is what I’d expect from the documentation. I’m having difficulty figuring out what the underlying rule is, since the two examples have the same input apart from the order and the same format. It seems to be to do with whether the first element of the array can be interpreted according to the format.
It looks like I have to put every call to datetime in a try-catch block and also test the result result for NaT, if I’m to detect any non-conforming input. This seems excessive – can anyone suggest a better way, or whether this is actually a bug I should try to report? Sometimes datetime throws an error if it can’t return a valid datetime object from a string input:
dt = datetime(["2026_06" "2026_06_13"], Format = "yyyy_MM_dd")
and sometimes it returns NaT:
dt = datetime(["2026_06_13" "2026_06"], Format = "yyyy_MM_dd")
dt =
1×2 datetime array
2026_06_13 NaT
The second result is what I’d expect from the documentation. I’m having difficulty figuring out what the underlying rule is, since the two examples have the same input apart from the order and the same format. It seems to be to do with whether the first element of the array can be interpreted according to the format.
It looks like I have to put every call to datetime in a try-catch block and also test the result result for NaT, if I’m to detect any non-conforming input. This seems excessive – can anyone suggest a better way, or whether this is actually a bug I should try to report? datetime, datetime nat, datetime error MATLAB Answers — New Questions

​

Leave a Reply

Your email address will not be published. Required fields are marked *