How to round milliseconds of datetime Format?

20 Ansichten (letzte 30 Tage)
Brett Mather
Brett Mather am 10 Jun. 2020
Beantwortet: Brett Mather am 29 Jun. 2020
Here's an example:
>> dt = datetime("098:17:17:34.475", 'InputFormat', 'DDD:HH:mm:ss.SSS', 'Format', 'DDD:HH:mm:ss.SSS')
dt =
datetime
098:17:17:34.475
>> SecsSinceNewYear = seconds(dt - datetime(dt.Year, 1, 0, 0, 0, 0, 0))
SecsSinceNewYear =
8529454.475
>> dt = datetime(0, 1, 0, 0, 0, SecsSinceNewYear, 'Format', 'DDD:HH:mm:ss.SSS')
dt =
datetime
098:17:17:34.474
>> string(dt)
ans =
"098:17:17:34.474"
>> dt.Format = 'DDD:HH:mm:ss.SSSSSSSSS'
dt =
datetime
098:17:17:34.474999999
Notice that the input ends in 475 milliseconds, but when displayed there seems to be a precision error that ends up not rounding and displays 474 milliseconds. So when I attempt to convert the datetime back into it's original string form the millisecnds have changed from 475 to 474.
Is there anyway to avoid this error introduced by converting these formats?

Akzeptierte Antwort

Brett Mather
Brett Mather am 29 Jun. 2020
Following up after getting support from MathWorks:
This was identified as a bug that exists in at least R2017b (maybe others) but is supposedly fixed in 2018a and later (I haven't checked as I'm using 2017b).
To further clarify the bug:
>> dt = datetime(0, 1, 0, 0, 0, 8.529454475000000e+06, 'Format', 'DDD:HH:mm:ss.SSS')
dt =
datetime
098:17:17:34.474
Notice that the double I input for 'seconds' in datetime ends in 475 milliseconds and the output from datetime formatted to show milliseconds shows 474.
To work around this in 2017b do the following to split the original double into 'seconds' and 'milliseconds' before input to datetime:
>> start = 8.529454475000000e+06;
>> s = floor(start);
>> ms = round((start - s)*1000);
>> dt = datetime(0, 1, 0, 0, 0, s, ms, 'Format', 'DDD:HH:mm:ss.SSS')
dt =
datetime
098:17:17:34.475

Weitere Antworten (0)

Kategorien

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

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by