fix(api): 修复 JSON 序列化错误
- 支持多种日期列名(date, Date, index, trade_date, datetime) - 添加对 Timestamp 对象的递归转换 - 修复 yfinance 返回数据中的 Timestamp 序列化问题
This commit is contained in:
@@ -205,12 +205,29 @@ def dataframe_to_json(df: pd.DataFrame) -> Dict:
|
|||||||
# 重置索引,将日期转为列
|
# 重置索引,将日期转为列
|
||||||
df_reset = df.reset_index()
|
df_reset = df.reset_index()
|
||||||
|
|
||||||
# 处理日期列
|
# 处理日期列(支持多种可能的列名)
|
||||||
if 'date' in df_reset.columns:
|
date_columns = ['date', 'Date', 'index', 'trade_date', 'datetime']
|
||||||
df_reset['date'] = df_reset['date'].dt.strftime('%Y-%m-%d')
|
for col in date_columns:
|
||||||
elif 'index' in df_reset.columns:
|
if col in df_reset.columns:
|
||||||
df_reset['index'] = pd.to_datetime(df_reset['index']).dt.strftime('%Y-%m-%d')
|
try:
|
||||||
df_reset = df_reset.rename(columns={'index': 'date'})
|
df_reset[col] = pd.to_datetime(df_reset[col]).dt.strftime('%Y-%m-%d')
|
||||||
|
# 统一重命名为 'date'
|
||||||
|
if col != 'date':
|
||||||
|
df_reset = df_reset.rename(columns={col: 'date'})
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 确保所有数据都是 JSON 可序列化的
|
||||||
|
for col in df_reset.columns:
|
||||||
|
if df_reset[col].dtype == 'object':
|
||||||
|
# 转换可能的 Timestamp 对象
|
||||||
|
try:
|
||||||
|
df_reset[col] = df_reset[col].apply(
|
||||||
|
lambda x: x.strftime('%Y-%m-%d') if hasattr(x, 'strftime') else x
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
# 转换为字典列表
|
# 转换为字典列表
|
||||||
records = df_reset.to_dict(orient='records')
|
records = df_reset.to_dict(orient='records')
|
||||||
@@ -220,8 +237,8 @@ def dataframe_to_json(df: pd.DataFrame) -> Dict:
|
|||||||
"count": len(records),
|
"count": len(records),
|
||||||
"columns": list(df_reset.columns),
|
"columns": list(df_reset.columns),
|
||||||
"date_range": {
|
"date_range": {
|
||||||
"start": df.index.min().strftime('%Y-%m-%d'),
|
"start": df.index.min().strftime('%Y-%m-%d') if hasattr(df.index.min(), 'strftime') else str(df.index.min()),
|
||||||
"end": df.index.max().strftime('%Y-%m-%d'),
|
"end": df.index.max().strftime('%Y-%m-%d') if hasattr(df.index.max(), 'strftime') else str(df.index.max()),
|
||||||
} if len(df) > 0 else None
|
} if len(df) > 0 else None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user