Could you please help me with this error? I have tried my suggestions that I found online but cannot get it to work. This is a visual that I need to display in Power BI using Python. Running into this error: TypeError: Object of type timedelta is not JSON serializable
test data:
import pandas as pd
data = {
'ID': [45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45],
'Group Name': ['Group 1', 'Group 1', 'Group 1', 'Group 1', 'Group 2',
'Group 3', 'Group 3', 'Group 3', 'Group 3',
'Group 3', 'Group 3', 'Group 3',' Group 4'],
'Event Description': ['frefref','rfgrtgth','ujuyjuyi','ikioloolo',
'uyuyjuyjuj','reerfgrvb','uyjhnuymk',
"ikuk",'trtrh','ikukiu',"ikiukiukuio",
"trgrhg","rtghrtyh","rhtyhyt"],
"Start Date": ["28/02/2022", "20/12/2022", "02/08/2022",
"01/01/2022", "25/11/2016", "20/12/2022",
"04/07/2019","07/04//2020","15//02//2016",
"31//07//2022","15//02//2016","31//07//2022",
"16//06//2015"],
"End Date": ["28///02///2022", "//20///12///2022", "//02///08///22",
"//01////01////22", "//25////11////16", "//17////06////24",
"//17/////06/////24","/////17/////06/////24",
"/17////////06////////24","////////17////////06////////24",
"/17////////////06////////////24"]
}
source = pd.DataFrame(data)
print(source)
import libraries:
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import datetime as dt
import plotly.express as px
import pandas as pd
import matplotlib.dates as mdates
import plotly.graph_objects as go
code to create a timeline visual:
# Convert 'Start Date' and 'End Date' to datetime format
source['Start Date'] = pd.to_datetime(source['Start Date'], format='%d-%m-%Y')
source['End Date'] = pd.to_datetime(source['End Date'], format='%d-%m-%Y')
# Calculate the difference in days between 'End Date' and 'Start Date'
source['diff'] = (source['End Date'] - source['Start Date']).dt.days
x = source['End Date']
# Reverse the DataFrame to match the reversed y-axis labels
source = source.iloc[::-1].reset_index(drop=True)
# Create a figure and axis
fig = px.timeline(source, x_start="Start Date", x_end="End Date", y="Event Description", color="Group Name",
hover_data={"Start Date": "|%Y-%m-%d", "End Date": "|%Y-%m-%d"},
labels={"Start Date": "Start Date", "End Date": "End Date"})
# Update tooltip text for ongoing events
today = pd.to_datetime('today').date()
fig.update_traces(hovertemplate='<b>%{y}</b><br>Start Date: %{customdata[0]}<br>End Date: %{customdata[1]}<br>',
selector=dict(name='Ongoing'),
customdata=[str(today), str(today)]) # Convert timedelta to string
# Update layout
fig.update_layout(
title='Timeline',
xaxis=dict(
title='Date',
tickformat='%Y'
),
yaxis=dict(
title='Group Name'
)
)
plt.tight_layout()
fig.show()
error message:
/databricks/python/lib/python3.10/site-packages/plotly/express/_core.py:1979: FutureWarning:
When grouping with a length-1 list-like, you will need to pass a length-1 tuple to get_group in a future version of pandas. Pass (name,)
instead of name
to silence this warning.
/databricks/python/lib/python3.10/site-packages/_plotly_utils/basevalidators.py:106: FutureWarning:
The behavior of DatetimeProperties.to_pydatetime is deprecated, in a future version this will return a Series containing python datetime objects instead of an ndarray. To retain the old behavior, call np.array
on the result
I spent two days trying to solve this. Tried many different approaches that I found online but my Python skills are not that great so hard to get it solved.
Lenka Wolfova is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.