How to keep the precision of datetime when taking into consideration time offsets
67 ビュー (過去 30 日間)
古いコメントを表示
I am writing a code that will convert the time into different readable (plotable) formats. For instance I have data that is reported in milliseconds, I would like to convert it to a 'HH:mm:ss.SSS' format. I am able to write code to do this. The issue is when I take into consideration a time offset, in a format 'HH:mm:ss.SSS', I lose the millisecond detail. Below is part of my code, I cannot share all of it.
if nargin < 4
pTimeOffsets = datetime('00:00:00.000',...
'Format','HH:mm:ss.SSS'); % this is the Time Offset, it is an optional argument and if left out is defaulted to nothing.
end
...
pConvertedTime = datetime(strcat(string(lHH),':',...
string(lmm),':',...
string(lss),'.',...
string(lSSS)),...
'Format','HH:mm:ss.SSS'); % this will take the milliseconds and convert into a datetime object.
%The desired precision is kept.
If I were to do this:
pConvertedTime = datetime(strcat(string(lHH),':',...%lHH is hour number
string(lmm),':',...%lmm is minute number
string(lss),'.',...%lss is second number
string(lSSS)),...%lSSS is millisecond number
'Format','HH:mm:ss.SSS') - pTimeOffsets; % offsets loses milliseconds precision
Any suggestions?
2 件のコメント
採用された回答
Steven Lord
2019 年 12 月 11 日
You don't actually want a datetime array, you want a duration array. That's easy. First remove the fractional seconds. There's no need to perform division, rounding, and multiplication for your lSSS.
lSSS2 = rem(pTimeInput, 1000);
The rest of your number is the number of seconds you want your duration to represent.
numSeconds = (pTimeInput-lSSS2)/1000;
Now build your duration.
d = seconds(numSeconds)+seconds(lSSS2)/1000
Because I built d using seconds it displays as seconds, but you can change its display Format. [This was, I believe, the main issue with your original code, but I find using seconds to be easier to explain than the arithmetic.]
d.Format = 'hh:mm:ss.SSS'
That looks to be in agreement with your pTimeInput data. Let's see them side-by-side to compare.
format longg
tt = timetable(d, pTimeInput)
その他の回答 (1 件)
参考
カテゴリ
Help Center および File Exchange で Dates and Time についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!