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)
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.