You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Streamlit中Pandas日期列显示格式异常问题求助

问题:Streamlit中dataframe_explorer组件导致日期列显示格式异常

问题详情

  • 已通过Pandas将日期列转换为仅含日期的格式(如2023-05-11、11 May 23),终端打印结果正常
  • 但在Streamlit中使用from streamlit_extras.dataframe_explorer import dataframe_explorer组件后,所有日期列被强制转回yyyy-mm-dd hh:mm:ss格式
  • 原始Datetime列格式为2023-05-11T18:00:00.000+01:00,转换日期列的代码如下:
def _get_date(self):
    self.df["Date"] = (
        pd.to_datetime(self.df[self.date], utc=True)
        .dt.tz_convert("Europe/London")
        .dt.date
    )
    self.df["Test"] = pd.to_datetime(self.df["Date"], format='%Y-%m-%d').dt.strftime('%d %b %y')
    self.df['Test2'] = pd.to_datetime(self.df['Datetime'])
    self.df["Test2"] = self.df['Test2'].astype(str)
    self.df["Test2"] = [d[0] for d in self.df["Test2"].str.split(" ")]

解决方案

方案1:将日期列转为字符串后传入组件

dataframe_explorer会自动识别日期类型并转换格式,将日期列转为字符串可避免这种强制转换:

# 把需要显示的日期列转为字符串类型
self.df["Date"] = self.df["Date"].astype(str)
self.df["Test"] = self.df["Test"].astype(str)
self.df["Test2"] = self.df["Test2"].astype(str)

# 传入dataframe_explorer组件
filtered_df = dataframe_explorer(self.df)
st.dataframe(filtered_df)

方案2:保留筛选功能并指定显示格式

如果需要保留组件的日期筛选功能,可通过Streamlit的column_config强制指定日期列的显示格式:

filtered_df = dataframe_explorer(self.df)

# 自定义列显示格式
st.dataframe(
    filtered_df,
    column_config={
        "Date": st.column_config.DateColumn(
            "Date",
            format="YYYY-MM-DD",
        ),
        "Test": st.column_config.TextColumn("Test"),
        "Test2": st.column_config.DateColumn(
            "Test2",
            format="YYYY-MM-DD",
        )
    }
)

原因说明

dataframe_explorer组件为了实现日期筛选功能,会自动检测DataFrame中的日期相关类型(包括datetime.date类型),并将其转换为带默认时分秒的datetime类型,导致显示时额外带上00:00:00。

内容的提问来源于stack exchange,提问作者enchanted_potato

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 23:32:41