How to round datetime array to nearest minute?

46 Ansichten (letzte 30 Tage)
Ziye
Ziye am 14 Sep. 2017
Kommentiert: Peter Perkins am 14 Sep. 2017
Sounds like quite a easy question but i've spent a lot of time and cant find the answer. Basically I have a datetime array, i want to reduce the precision to minute so that second and beyond(millisecond etc.) are all changed to zero. is there any fast way to do so? Many Thanks

Akzeptierte Antwort

Steven Lord
Steven Lord am 14 Sep. 2017
You can use the dateshift function to do this. If you always want the result to be no later than the input, use 'start' on its own.
% Create some sample data
sampleData = datetime('now')
% Modify the display format of the sample data to show fractional seconds
sampleData.Format = 'dd-MMM-uuuu HH:mm:ss.SSS'
% Shift it to the start of the minute, throwing away seconds and fractional seconds
startOfMinute = dateshift(sampleData, 'start', 'minute')
If you want the result to be rounded to the start of the nearest minute, which could be later than the input datetime, use 'start' with 'nearest'.
% Create a sample datetime in the second half of the minute and set its format
sampleData = datetime(2017, 9, 14, 09, 52, 47.234, 'Format', ...
'dd-MMM-uuuu HH:mm:ss.SSS')
% Rounding should give 9:53 on September 14, 2017 since
% that's closer to sampleData than 9:52 on September 14, 2017
result = dateshift(sampleData, 'start', 'minute', 'nearest')

Weitere Antworten (1)

Ziye
Ziye am 14 Sep. 2017
Ok I just happen to find a solution by create a new datetime array using year month day hour minute second(0) of the original datetime array. but any other answers are welcomded

Kategorien

Mehr zu Dates and Time finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by