How to round datetime array to nearest minute?

조회 수: 46 (최근 30일)
Ziye
Ziye 2017년 9월 14일
댓글: Peter Perkins 2017년 9월 14일
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

채택된 답변

Steven Lord
Steven Lord 2017년 9월 14일
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')

추가 답변 (1개)

Ziye
Ziye 2017년 9월 14일
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
  댓글 수: 1
Peter Perkins
Peter Perkins 2017년 9월 14일
See Steve's suggestion below, i.e. dateshift.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Dates and Time에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by