How to convert nanoseconds timestamp to DateTime structure?

64 次查看(过去 30 天)
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.

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