How to convert nanoseconds timestamp to DateTime structure?

조회 수: 53 (최근 30일)
A.
A. 2015년 2월 11일
편집: Stephen23 2015년 2월 11일
What is the f that does
f(1398902555536968492)-->2014.08.29 05:35:19:7600000
?
  댓글 수: 1
Stephen23
Stephen23 2015년 2월 11일
편집: Stephen23 2015년 2월 11일
How is your number 1398902555536968492 stored? Numerics of class double only have 15-17 digits of precision (53 bits), whereas this number is given here with 19 digits, so it is not precisely representable using a double. uint64 goes up to 18446744073709551615.

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

답변 (2개)

Peter Perkins
Peter Perkins 2015년 2월 11일
You say "nanoseconds", but you have not said "since when". So
>> t = datetime('2014.08.29 05:35:19:7600000','Format','yyyy.MM.dd HH:mm:ss:SSSSSSS')
t =
2014.08.29 05:35:19:7600000
>> t - seconds(1398902555536968492/1e9)
ans =
1970.05.01 05:32:44:2230314
doesn't seem all that likely.
Perhaps you made a typing error and you really mean "nanoseconds since 1-Jan-1970 00:00:00". (Stephen, I think you dropped "2" of the end of the big number in your code.) Modulo what Stephen said about needing to store your count in uint64,
>> ns = uint64(1398902555536968492)
ns =
1398902555536968492
>> wholeSecs = floor(double(ns)/1e9)
wholeSecs =
1398902555
>> fracSecs = double(ns - uint64(wholeSecs)*1e9)/1e9
fracSecs =
0.536968492
>> t = datetime(wholeSecs,'ConvertFrom','posixTime','Format','yyyy.MM.dd HH:mm:ss.SSSSSSSSS') + seconds(fracSecs)
t =
2014.05.01 00:02:35.536968492
Hope this helps.
  댓글 수: 1
Stephen23
Stephen23 2015년 2월 11일
편집: Stephen23 2015년 2월 11일
Thank you for the tip about the missing '2'.

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


Stephen23
Stephen23 2015년 2월 11일
편집: Stephen23 2015년 2월 11일
This finds your start epoche (01-May-1970 05:32:44, apparently), and converts a uint64 value (of nanoseconds since that epoche) to a standard MATLAB datenumber:
X = 60*60*24e9;
D = datenum('2014.08.29 05:35:19:760','yyyy.mm.dd HH:MM:SS:FFF');
N = uint64(1398902555536968492);
% identify epoche:
Z = D - double(N)/X;
A couple of test cases:
>> datestr(0+Z)
ans = '01-May-1970 05:32:44'
>> datestr(double(N)/X+Z)
ans = '29-Aug-2014 05:35:19'
>> M = uint64(1398902556536968492); % one second later
>> datestr(double(M)/X+Z)
ans = '29-Aug-2014 05:35:20'
It is important to realize that this conversion loses precision (the result does not have nanosecond precision). You can use datestr 's options to select the desired timestamp format.
EDIT: replaced missing '2', thanks to Peter Perkins.
Given the correct epoche start of 1970-05-01, is it possible that this should actually be a UNIX time , starting 1970-01-01 ? If so, then you can find several discussions about this on Answers , and also several submissions on File Exchange .

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by