Skip to content

Commit

Permalink
Support JSON serialization of numpy datetime64 arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
jonmmease committed Jan 13, 2021
1 parent 7540acf commit 050dd8a
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion packages/python/plotly/_plotly_utils/basevalidators.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def copy_to_readonly_numpy_array(v, kind=None, force_numeric=False):
# datatype. This works around cases like np.array([1, 2, '3']) where
# numpy converts the integers to strings and returns array of dtype
# '<U21'
if new_v.dtype.kind not in ["u", "i", "f", "O"]:
if new_v.dtype.kind not in ["u", "i", "f", "O", "M"]:
new_v = np.array(v, dtype="object")

# Set new array to be read-only
Expand Down
9 changes: 7 additions & 2 deletions packages/python/plotly/_plotly_utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,13 @@ def encode_as_numpy(obj):

if obj is numpy.ma.core.masked:
return float("nan")
else:
raise NotEncodable
elif isinstance(obj, numpy.ndarray):
try:
return numpy.datetime_as_string(obj).tolist()
except TypeError:
pass

raise NotEncodable

@staticmethod
def encode_as_datetime(obj):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,15 @@ def test_datetime_dot_date(self):
j1 = _json.dumps(a, cls=utils.PlotlyJSONEncoder)
assert j1 == '["2014-01-01", "2014-01-02"]'

def test_numpy_datetime64(self):
a = pd.date_range("2011-07-11", "2011-07-13", freq="D").values
j1 = _json.dumps(a, cls=utils.PlotlyJSONEncoder)
assert (
j1 == '["2011-07-11T00:00:00.000000000", '
'"2011-07-12T00:00:00.000000000", '
'"2011-07-13T00:00:00.000000000"]'
)

def test_pil_image_encoding(self):
import _plotly_utils

Expand Down

0 comments on commit 050dd8a

Please sign in to comment.