sorting table according to date/time

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

 採用された回答

Star Strider
Star Strider 2020 年 10 月 28 日

1 投票

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.)

その他の回答 (3 件)

Steven Lord
Steven Lord 2020 年 10 月 28 日

1 投票

which failed, probably becasue I am not defining the AM/PM symbols.
According to the table in the description of the Format property of datetime objects include the character a in the Format and/or InputFormat values to handle AM/PM. I had to make three additional changes to your InputFormat, each prompted by a warning and/or error message.
Using HH for hours in 24-hour clock notation is incompatible with also specifying the day period (AM/PM) so I changed it to hh (hour, 12-hour clock notation.)
Using MM (month) and DD (day of year) are incompatible, so I changed DD to dd (day of month).
Lower-case ss is for seconds, upper-case S are for the digits of fractional seconds.
s = '6/29/2020 12:39:32.910 AM'
t=datetime(s,'InputFormat', 'MM/dd/yyyy hh:mm:ss.SSS a')
KSSV
KSSV 2020 年 10 月 28 日

0 投票

Convert the dates you have into class of datetime using the function datetime and then you can use sort function. Read about datetime.
Carol pacheco
Carol pacheco 2021 年 9 月 28 日

0 投票

Hello,
I have a dataset that I need to group the data into over a period of fifteen days (two weeks), however I have a total of 23 weeks. Could someone give me a little help or guidance ?

カテゴリ

ヘルプ センター および File ExchangeDates and Time についてさらに検索

製品

質問済み:

2020 年 10 月 28 日

回答済み:

2021 年 9 月 28 日

Community Treasure Hunt

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

Start Hunting!

Translated by