I’m displaying a wide (many columns) pandas dataframe within Streamlit which contains a lot (15+) of datetime columns, although they are only being used for dates not the times. These currently appear as 23-10-2024 00:00:00. I’d like to format them for display as just the dates 2024/10/23 or something similar. What’s the easiest way to do this in bulk, as a single “do all dates like this” rather than individually, so that I keep a consistent look, save on long repetitive code and allow for future date columns that might be added?
Things I’ve tried:
Convert the datetimes to dates in the dataframe. This doesn’t play well with the st datepicker, which I’m using to filter the dataframe
Using column-configs, but I’ll have to make one for every column, so that’s doing it one-by-one
Using Pandas styling, which also requires to style each column individually.
import streamlit as st
import pandas as pd
# Sample wide dataframe with many datetime columns
columns = [f'date_col_{i}' for i in range(1, 20)]
# Generating a DataFrame with datetime columns
data = {col: pd.date_range(start='2024-01-01', periods=5, freq='D') for col in columns}
df = pd.DataFrame(data)
# Formatting datetime columns to just display the date in 'YYYY/MM/DD' format
def format_datetime_columns(df):
for col in df.columns:
if pd.api.types.is_datetime64_any_dtype(df[col]):
df[col] = df[col].dt.strftime('%Y/%m/%d')
return df
# Apply formatting
formatted_df = format_datetime_columns(df)
st.title('Formatted Date Columns')
st.dataframe(formatted_df)