KeyError: <class 'pandas._libs.tslibs.timestamps.Timestamp'> when making datetime slider

Summary

I am trying to make a datetime slider but I am getting an error:

KeyError: <class ‘pandas._libs.tslibs.timestamps.Timestamp’>

KeyError: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
File "/Users/indapa/miniconda3/lib/python3.9/site-packages/streamlit/scriptrunner/script_runner.py", line 557, in _run_script
    exec(code, module.__dict__)
File "pages/Production_Over_Time.py", line 21, in <module>
    date_range = st.sidebar.slider('Select Date Range',
File "/Users/indapa/miniconda3/lib/python3.9/site-packages/streamlit/elements/slider.py", line 152, in slider
    return self._slider(
File "/Users/indapa/miniconda3/lib/python3.9/site-packages/streamlit/elements/slider.py", line 227, in _slider
    data_type = SUPPORTED_TYPES[type(value[0])]

My code is:

solar_file = Path(__file__).parent.parent / "solar_production.csv"
data = pd.read_csv(solar_file, index_col=0)
data['Time'] = pd.to_datetime(data['Time'], errors='coerce')
data = data[pd.notna(data['Time'])]
start_date = data['Time'].min()
end_date = data['Time'].max()

# create a date slidebar to select date range
date_range = st.sidebar.slider('Select Date Range', start_date, end_date, (start_date, end_date))
st.write('You selected:', date_range)

I am not sure what the issue is. Perhaps I should not be calling to_datetime on my pandas dataframe?

The type of start_date and end_date is pandas.Timestamp, but st.slider only accepts datetime.datetime. You can use .to_pydatetime to convert the former to the latter.

1 Like

Hi! I was having the same issue and the problem turned out to be in the last argument date_range = st.sidebar.slider(‘Select Date Range’, start_date, end_date, (start_date, end_date))

the only accepted format for the value argument is somenthing like that:
(datetime.datetime(2023,1,1), datetime.datetime(2023,7,1))

so I had to do several transformation to get year, month and day of the dates I want to be in the argument “Value”. the result is something like this:

yearmin = df['Date'].min().year
monthmin = df['Date'].min().month
daymin = df['Date'].min().day

yearmax = df['Date'].max().year
monthmax = df['Date'].max().month
daymax = df['Date'].max().day


PRE_SELECTED_DATES = (datetime.datetime(yearmin,monthmin,daymin), datetime.datetime(yearmax,monthmax,daymax ))

dates_selection = st.slider("date selector",
                            min_value = min(df['Date']),
                            max_value = max(df['Date']),
                            value =(PRE_SELECTED_DATES))