summaryrefslogtreecommitdiff
path: root/msgpack/ext.py
diff options
context:
space:
mode:
authorInada Naoki <songofacandy@gmail.com>2019-12-11 23:48:16 +0900
committerGitHub <noreply@github.com>2019-12-11 23:48:16 +0900
commit2186455d1579affc33253484d9445f7bdf3f7c29 (patch)
tree4081e93d9815fb0a63a81e9d3a55b1f971b02ac6 /msgpack/ext.py
parent5fd611909319d03200774ea3c7a6ae16dbd26c12 (diff)
downloadmsgpack-python-2186455d1579affc33253484d9445f7bdf3f7c29.tar.gz
Support datetime. (#394)
Diffstat (limited to 'msgpack/ext.py')
-rw-r--r--msgpack/ext.py27
1 files changed, 26 insertions, 1 deletions
diff --git a/msgpack/ext.py b/msgpack/ext.py
index c7efff6..09adb34 100644
--- a/msgpack/ext.py
+++ b/msgpack/ext.py
@@ -1,12 +1,18 @@
# coding: utf-8
from collections import namedtuple
+import datetime
import sys
import struct
PY2 = sys.version_info[0] == 2
+
if not PY2:
long = int
+ try:
+ _utc = datetime.timezone.utc
+ except AttributeError:
+ _utc = datetime.timezone(datetime.timedelta(0))
class ExtType(namedtuple("ExtType", "code data")):
@@ -131,7 +137,7 @@ class Timestamp(object):
data = struct.pack("!Iq", self.nanoseconds, self.seconds)
return data
- def to_float_s(self):
+ def to_float(self):
"""Get the timestamp as a floating-point value.
:returns: posix timestamp
@@ -139,6 +145,12 @@ class Timestamp(object):
"""
return self.seconds + self.nanoseconds / 1e9
+ @staticmethod
+ def from_float(unix_float):
+ seconds = int(unix_float)
+ nanoseconds = int((unix_float % 1) * 1000000000)
+ return Timestamp(seconds, nanoseconds)
+
def to_unix_ns(self):
"""Get the timestamp as a unixtime in nanoseconds.
@@ -146,3 +158,16 @@ class Timestamp(object):
:rtype: int
"""
return int(self.seconds * 1e9 + self.nanoseconds)
+
+ if not PY2:
+
+ def to_datetime(self):
+ """Get the timestamp as a UTC datetime.
+
+ :rtype: datetime.
+ """
+ return datetime.datetime.fromtimestamp(self.to_float(), _utc)
+
+ @staticmethod
+ def from_datetime(dt):
+ return Timestamp.from_float(dt.timestamp())