File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ TAI64N encoding and decoding.
3
+ TAI64N encodes nanosecond-accuracy timestamps and is supported by logstash.
4
+ @see: U{http://cr.yp.to/libtai/tai64.html}.
5
+ """
6
+
7
+ from __future__ import unicode_literals
8
+
9
+ import struct
10
+
11
+ _STRUCTURE = b">QI"
12
+ _OFFSET = (2 ** 62 ) + 10 # last 10 are leap seconds
13
+
14
+
15
+ def encode (timestamp ):
16
+ """
17
+ Convert seconds since epoch to TAI64N string.
18
+ @param timestamp: Seconds since UTC Unix epoch as C{float}.
19
+ @return: TAI64N-encoded time, as C{unicode}.
20
+ """
21
+ seconds = int (timestamp )
22
+ nanoseconds = int ((timestamp - seconds ) * 1000000000 )
23
+ seconds = seconds + _OFFSET
24
+ return struct .pack (_STRUCTURE , seconds , nanoseconds )
25
+
26
+
27
+ def decode (tai64n ):
28
+ """
29
+ Convert TAI64N string to seconds since epoch.
30
+ Note that dates before 2013 may not decode accurately due to leap second
31
+ issues. If you need correct decoding for earlier dates you can try the
32
+ tai64n package available from PyPI (U{https://pypi.python.org/pypi/tai64n}).
33
+ @param tai64n: TAI64N-encoded time, as C{unicode}.
34
+ @return: Seconds since UTC Unix epoch as C{float}.
35
+ """
36
+ seconds , nanoseconds = struct .unpack (_STRUCTURE , tai64n )
37
+ seconds -= _OFFSET
38
+ return seconds + (nanoseconds / 1000000000.0 )
You can’t perform that action at this time.
0 commit comments