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