Streamlit中st.dataframe()显示Datetime格式异常问题求助
解决Streamlit中Excel日期/时间间隔显示异常问题
问题原因
- Date列多余时间:Excel里的纯日期被pandas解析为
datetime64类型,默认带00:00:00时分秒,Streamlit会完整渲染这部分内容; - interval列显示数字:Excel的时间间隔(如
hh:mm格式)被解析为timedelta类型,Streamlit默认将其转为总天数的浮点数展示,导致显示异常。
解决方案
下面提供两种处理方式,按需选择:
方式1:转为字符串格式(完全匹配原始显示)
直接将日期和时间间隔列转为自定义格式的字符串,彻底避免格式问题:
# File Upload uploaded_file = st.file_uploader( "Upload inventory file for past week estimates in **excel** format." ) sheet_name = st.text_input("Add the name of the sheet to select data from. **Default = first sheet**") if uploaded_file is not None: try: # 读取Excel文件 if sheet_name: historical_interval_data = pd.read_excel(uploaded_file, sheet_name=sheet_name) else: historical_interval_data = pd.read_excel(uploaded_file) # 处理Date列:转为YYYY-MM-DD格式字符串(可根据原始格式调整) if 'Date' in historical_interval_data.columns: historical_interval_data['Date'] = historical_interval_data['Date'].dt.strftime('%Y-%m-%d') # 处理interval列:将timedelta转为hh:mm格式字符串 if 'interval' in historical_interval_data.columns: def format_timedelta(td): total_seconds = int(td.total_seconds()) hours = total_seconds // 3600 minutes = (total_seconds % 3600) // 60 return f"{hours:02d}:{minutes:02d}" historical_interval_data['interval'] = historical_interval_data['interval'].apply(format_timedelta) # 展示处理后的数据 st.dataframe(historical_interval_data) except ValueError: st.error("**Error**: The sheet name is incorrect.")
方式2:保留原始数据类型,优化Streamlit显示
如果需要保留datetime/timedelta类型用于后续计算,可通过Streamlit的st.dataframe自定义格式参数调整显示:
# File Upload uploaded_file = st.file_uploader( "Upload inventory file for past week estimates in **excel** format." ) sheet_name = st.text_input("Add the name of the sheet to select data from. **Default = first sheet**") if uploaded_file is not None: try: # 读取Excel文件 if sheet_name: historical_interval_data = pd.read_excel(uploaded_file, sheet_name=sheet_name) else: historical_interval_data = pd.read_excel(uploaded_file) # 定义时间间隔格式化函数 def format_timedelta(td): total_seconds = int(td.total_seconds()) hours = total_seconds // 3600 minutes = (total_seconds % 3600) // 60 return f"{hours:02d}:{minutes:02d}" # 新建显示用的间隔列,保留原列用于计算 historical_interval_data['interval_display'] = historical_interval_data['interval'].apply(format_timedelta) # 自定义列显示配置 column_config = { "Date": st.column_config.DateColumn( "Date", format="YYYY-MM-DD", help="Inventory date" ), "interval_display": st.column_config.TextColumn( "Interval", help="Time interval" ) } # 展示处理后的数据 st.dataframe(historical_interval_data, column_config=column_config) except ValueError: st.error("**Error**: The sheet name is incorrect.")
注意事项
- 替换代码中的
'Date'和'interval'为你实际的列名; - 日期格式
'%Y-%m-%d'可根据Excel原始显示调整(比如'%m/%d/%Y'); - 时间间隔的格式化函数可按需修改,比如要显示秒数就加上
seconds = total_seconds % 60并调整返回格式。
内容的提问来源于stack exchange,提问作者Prakhar Rathi
相关产品推荐
相关产品推荐

