python
type_error
ai_generated
true
TypeError: float() argument must be a string or a real number, not 'datetime.datetime'
ID: python/matplotlib-date-converter-error
80%Fix Rate
85%Confidence
0Evidence
2024-04-09First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
Passing naive datetime objects directly to plot() without registering a date converter, or mixing datetime with numeric on the same axis.
generic中文
在未注册日期转换器的情况下将 naive datetime 对象直接传给 plot(),或在同一轴上混用 datetime 与数值。
Workarounds
-
94% success
import matplotlib.dates as mdates dates = mdates.date2num(dt_list) ax.plot(dates, values) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) -
90% success
import pandas as pd pd.plotting.register_matplotlib_converters() ax.plot(df['date'], df['value'])
Dead Ends
Common approaches that don't work:
-
75% fail
Strings become categorical labels, destroying the time axis ordering and tick formatting.
-
60% fail
Mixing converted and unconverted series still triggers the float() error on the unconverted one.