Prevent error when creating st.date_input

Summary

I’ve created a dashboard using streamlit, one of the charts I’ve made needed a date filter, where the user can pick a time frame between two dates to change the chart to their requirements. I’ve used the below code to do this, everything works fine but when you pick your two dates, there is an error that pops up when you select your start date but have not yet selected your end date, this isn’t very user friendly so I was wondering if there’s a way to display an info box or something similar instead to prompt them to select an end date.

Steps to reproduce

Code snippet:

format = 'DD,MM,YYYY'
start_date = df['created_date'].min()
end_date = df['created_date'].max()
start_date, end_date = st.date_input('Start date - End date :', (start_date, end_date))
if start_date < end_date:
    pass
else:
    st.error('Error: End date must fall after start date.')

mask = (df['created_date'].dt.date > start_date) & (df['created_date'].dt.date <= end_date)
df = df.loc[mask]   

When the user selects the start date and before they pick their end date, the error that pops up is:

ValueError: not enough values to unpack (expected 2, got 1)

Could this be fixed with an if statement or is there another way?

Hi @Dom2108, welcome to the forum!

The good news is, the start date will always be less than the end date, so you don’t have to worry about that. The tricky thing is, when you first click a start date, streamlit immediately returns the result, even though you might be about to select and end date, too.

Here’s how I like to handle that:


val = st.date_input(
    "Start date - End date:",
    value=[start_date, end_date],
)
try:
    start_date, end_date = val
except ValueError:
    st.error("You must pick a start and end date")
    st.stop() # this makes sure that they pick a date before moving on, if you want that
1 Like