How to remove decimals digits from datetime arrays?

Hi,
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?

2 Comments

"I have a datetime array in the format 'yyyy-MM-dd HH:mm:ss.SSS'
Which of these do you actually want to achieve?:
  1. change the displayed format (this is totally independent of the stored date/time information), or
  2. round the stored date/time information to a particular unit/magnitude (this is totally independent of the format).
Of course both is also possible, but that would still mean two separate step which are unrelated to each other.
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

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.

3 Comments

Many thanks!!! This is exactly what I was looking for :)
Note that this is truncating the seconds to two decimal places (as Stephen says in his answer). If you wish to round to two decimal places, replace fix with round in the calculation of S.
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)

Categories

Products

Release

R2020b

Tags

Community Treasure Hunt

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

Start Hunting!