MATLAB: Sorting table according to date/time

datenumdatetimeMATLAB

Hi,
I have a table with a TimeStamp column with the format '6/29/2020 12:39:32.910 AM'. I want to sort the table in acesending order but by default Matlab treats the column as a string. I have tried using datetime to define the column as dat format:
>> t=datetime(T1T2.TimeStamp,'InputFormat', 'MM/DD/yyyy HH:mm:ss.sss')
which failed, probably becasue I am not defining the AM/PM symbols.
What is the best/easiest way to sort this table according to the date value?
Many thanks,
Ben

Best Answer

There are problems with the 'InputFormat' format string.
Try this:
t=datetime(T1T2.TimeStamp,'InputFormat', 'MM/dd/yyyy hh:mm:ss.SSS a')
producing:
t =
datetime
29-Jun-2020 00:39:32
Note that the hours need to be ‘hh’ not ‘HH’ for AM/PM times, the days are ‘dd’ not ‘DD’, and the ‘a’ denotes that the format is in AM/PM. (I created a temporary variable to replace the table reference to test this and make certain that it works.)