Skip to content

Commit 050dd8a

Browse files
committed
Support JSON serialization of numpy datetime64 arrays
1 parent 7540acf commit 050dd8a

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

Diff for: packages/python/plotly/_plotly_utils/basevalidators.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def copy_to_readonly_numpy_array(v, kind=None, force_numeric=False):
146146
# datatype. This works around cases like np.array([1, 2, '3']) where
147147
# numpy converts the integers to strings and returns array of dtype
148148
# '<U21'
149-
if new_v.dtype.kind not in ["u", "i", "f", "O"]:
149+
if new_v.dtype.kind not in ["u", "i", "f", "O", "M"]:
150150
new_v = np.array(v, dtype="object")
151151

152152
# Set new array to be read-only

Diff for: packages/python/plotly/_plotly_utils/utils.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,13 @@ def encode_as_numpy(obj):
184184

185185
if obj is numpy.ma.core.masked:
186186
return float("nan")
187-
else:
188-
raise NotEncodable
187+
elif isinstance(obj, numpy.ndarray):
188+
try:
189+
return numpy.datetime_as_string(obj).tolist()
190+
except TypeError:
191+
pass
192+
193+
raise NotEncodable
189194

190195
@staticmethod
191196
def encode_as_datetime(obj):

Diff for: packages/python/plotly/plotly/tests/test_optional/test_utils/test_utils.py

+9
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,15 @@ def test_datetime_dot_date(self):
277277
j1 = _json.dumps(a, cls=utils.PlotlyJSONEncoder)
278278
assert j1 == '["2014-01-01", "2014-01-02"]'
279279

280+
def test_numpy_datetime64(self):
281+
a = pd.date_range("2011-07-11", "2011-07-13", freq="D").values
282+
j1 = _json.dumps(a, cls=utils.PlotlyJSONEncoder)
283+
assert (
284+
j1 == '["2011-07-11T00:00:00.000000000", '
285+
'"2011-07-12T00:00:00.000000000", '
286+
'"2011-07-13T00:00:00.000000000"]'
287+
)
288+
280289
def test_pil_image_encoding(self):
281290
import _plotly_utils
282291

0 commit comments

Comments
 (0)