How to remove decimals digits from datetime arrays?

9 views (last 30 days)
I have a datetime array in the format 'yyyy-MM-dd HH:mm:ss.SSS', and I want to round down or remove only the third decimal digit. E.g. the output should be 'yyyy-MM-dd HH:mm:ss.SS'. It seems that I cant use functions like round, floor or ceil in datetime arrays, as it prompts an error message that suggest I use dateshift instead. However, dateshift does not seem to handle rounding miliseconds (it works if I just wanted to remove/round all decimals, but that is not what I want... like I said, I am interested in keeping 2 decimal digits only).
I've tried converting the array into datenum or extract only the 'seconds' part as a double. Also tried to change just the format but that does not really remove the third digit from the database (it seems like it is only a visual change). I think there should be an easier way to do this. Does someone know how to do this?
Guillermo Pérez Castro
Guillermo Pérez Castro on 26 Jan 2022
Hi, thanks for the reply, I am actually interested in changing the stored value, that is, to round the stored date/time information to 2 decimal digits instead of 3.

Sign in to comment.

Accepted Answer

Stephen23 on 26 Jan 2022
Edited: Stephen23 on 26 Jan 2022
Assuming that the goal is to truncate at some precision (which is totally independent of the FORMAT), then this works:
T = datetime(2022,01,02,03,04,05.6789, 'Format','yyyy-MM-dd HH:mm:ss.SSS')
T = datetime
2022-01-02 03:04:05.678
S = fix(mod(second(T),1)*100)/100
S = 0.6700
U = dateshift(T,'start','second') + seconds(S)
U = datetime
2022-01-02 03:04:05.670
Of course if you do not want to change the underlying data then you can simply change the FORMAT property.
Guillermo Pérez Castro
Guillermo Pérez Castro on 26 Jan 2022
Thanks for the comment, but in this case, I do wish to truncate the decimals, so this solution will do just fine.

Sign in to comment.

More Answers (0)





Community Treasure Hunt

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

Start Hunting!