- change the displayed format (this is totally independent of the stored date/time information), or
- round the stored date/time information to a particular unit/magnitude (this is totally independent of the format).
How to remove decimals digits from datetime arrays?
21 views (last 30 days)
Show older comments
Guillermo Pérez Castro
on 26 Jan 2022
Commented: Guillermo Pérez Castro
on 26 Jan 2022
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
Stephen23
on 26 Jan 2022
Edited: Stephen23
on 26 Jan 2022
"I have a datetime array in the format 'yyyy-MM-dd HH:mm:ss.SSS'
Which of these do you actually want to achieve?:
Of course both is also possible, but that would still mean two separate step which are unrelated to each other.
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')
S = fix(mod(second(T),1)*100)/100
U = dateshift(T,'start','second') + seconds(S)
Of course if you do not want to change the underlying data then you can simply change the FORMAT property.
3 Comments
Les Beckham
on 26 Jan 2022
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.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!