Plotly中时间戳无法JSON序列化问题求助
Hey there! Let's work through this timestamp JSON serialization issue you're facing with Plotly. As someone who's been in your shoes when starting out with Python and visualization libraries, I know how annoying these little hiccups can be—so let's break it down.
First, why does this happen? Plotly under the hood uses JSON to pass data around, but Python's native datetime objects (or raw Unix timestamps as plain numbers) aren't natively JSON-serializable. That's the root of the error you're seeing.
Here are a few straightforward fixes depending on what kind of timestamp data you're working with:
1. If you're using Python datetime objects
The easiest fix is to convert your datetime objects into ISO-formatted strings (this is JSON-friendly and Plotly can recognize it as a date). Here's an example:
import plotly.express as px import datetime # Convert datetime objects to ISO strings timestamps = [ datetime.datetime.now(), datetime.datetime.now() + datetime.timedelta(hours=1) ] iso_timestamps = [dt.isoformat() for dt in timestamps] data = { "timestamp": iso_timestamps, "value": [10, 20] } fig = px.scatter(data, x="timestamp", y="value") # Explicitly tell Plotly the x-axis is a date type fig.update_xaxes(type='date') fig.show()
2. If you're working with Unix timestamps (e.g., 1620000000 as seconds since epoch)
You'll want to convert these to either datetime objects or ISO strings first. Using pandas makes this super simple:
import plotly.express as px import pandas as pd # Sample Unix timestamp data (in seconds) data = { "timestamp": [1620000000, 1620003600], "value": [10, 20] } df = pd.DataFrame(data) # Convert Unix timestamps to pandas datetime objects df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s') # Plotly automatically recognizes pandas datetime columns fig = px.scatter(df, x="timestamp", y="value") fig.show()
Pro Tip: Use pandas if you can!
Plotly plays incredibly well with pandas datetime64 columns—you won't have to manually handle serialization at all. If you're not already using pandas for your data, it's worth learning the basics for data visualization tasks like this.
Give these methods a try, and let me know if you run into any more issues!
内容的提问来源于stack exchange,提问作者Ann

