Skip to content

Conversation

@emilykl
Copy link
Contributor

@emilykl emilykl commented Nov 10, 2025

Closes #3957, closes #5355

Fixes an issue where numpy datetimes with nanosecond precision, contained in a Python list and passed to a go trace constructor, were treated as integers rather than dates, and displayed on a numerical axis rather than a date axis.

This is more severe than it seems at first glance, since pandas Timestamp objects (which are represented by the numpy datetime64 datatype under the hood) use nanosecond precision by default, even when not required, so it is very easy to create a nanosecond precision datetime without intending to.

import pandas as pd
x = pd.to_datetime('2025-09-26')
print(x.unit)
# output: ns

The issue

Before this fix, the following code produces the incorrect result below. The x-axis should be a date axis, but instead it shows up as a numeric axis with very large numbers.

import pandas as pd
import plotly.graph_objs as go

x_vals = list(pd.to_datetime(['2025-01-01', '2025-01-02', '2025-01-03']).to_numpy())
y_vals = [10, 20, 15]
fig = go.Figure([go.Scatter(x=x_vals, y=y_vals, mode='lines+markers')])
fig.show()
Screenshot 2025-11-11 at 11 22 55 AM

The fix

These nanosecond-precision datetimes are converted to ints during the coercion step; specifically by a call to the numpy .item() function which converts a single value from a numpy type to a built-in Python type. For datetime64 types with microsecond precision or less, a call to .item() returns a Pandas datetime type. But since the Pandas datetime does not support any precision greater than microseconds, calling .item() on a datetime64 with nanosecond precision or greater simply returns a large integer.

This PR resolves the issue by adding an additional check to verify whether the value is a datetime64 with nanosecond precision, and if so, casts it to microsecond precision before calling .item().

To test

Run the code snippet given under "The issue" above. On this branch, it should produce a chart with the x-axis being a date axis:
Screenshot 2025-11-11 at 11 21 58 AM

@emilykl emilykl force-pushed the fix-np-date-handling-issue branch 3 times, most recently from 45d28d6 to 0b32cae Compare November 11, 2025 16:29
@emilykl emilykl force-pushed the fix-np-date-handling-issue branch from 0b32cae to 0a13e4f Compare November 11, 2025 16:30
@emilykl emilykl requested a review from camdecoster November 11, 2025 16:41
@emilykl emilykl marked this pull request as ready for review November 11, 2025 16:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

plotly 6.3.0 does not work with numpy datetime Incorrect handling of np.datetime64[ns] date values

2 participants