Search code examples
pythonpandasstreamlit

double ended slider that indicate to some specific dates in stream lit app


I am building an streamlit app. I have a Data Frame with start, end and activity date. I want to make a double ended slider which starts from the first date and end to the end date and also indicate and show the active date (pointing to the active date) per ID.

I know how to make the slider indicating to the first and last dates and the index date only for one ID, but it is not the double ended slider, and I want to show index date per id on slider.

id       first_month        last_month   Active_date  
PT1      2011-06-01         2019-10-01   2015-10-01
PT3      2020-09-01         2022-06-01   2021-10-01
df['first_month_active'] = pd.to_datetime(df['first_month_active'])
start_dt = st.sidebar.date_input('Start date', value=df['first_month_active'].min())

df['last_month_active'] = pd.to_datetime(df['last_month_active'])
end_dt = st.sidebar.date_input('End date', value=df['last_month_active'].max())

#If we agree that index date is 
df['Active_date'] = pd.to_datetime(df['Active_date'])
index_dt = st.sidebar.date_input('Index date', value="2015-10-01")

st.write(start_dt)

cols1,_ = st.columns((3,2)) # To make it narrower
format = 'MMM DD,YYYY'  # format output

max_days = end_dt-start_dt

slider = cols1.slider('Select date', min_value=start_dt, value=index_dt ,max_value=end_dt, format=format)

Solution

  • If you want the slider to be double-ended, then you need to pass a list or tuple into its initial value.

    slider = cols1.slider('Select date', min_value=start_dt, value=[start_dt,index_dt] ,max_value=end_dt, format=format)
    

    From Streamlit's Documentation on slider

    Parameter: value (a supported type or a tuple/list of supported types or None)

    The value of the slider when it first renders. If a tuple/list of two values is passed here, then a range slider with those lower and upper bounds is rendered. For example, if set to (1, 10) the slider will have a selectable range between 1 and 10. Defaults to min_value.

    PS. Make sure to cast your value to datetime.date type in your line defining index_dt