Datetime slider

Dear,

I would like to create a slider where you can choose a period between two dates. First of all, from what I read on the website, a slider is only available to display integers? Is this correct?

Second, there seems to be a bug with the st.date_input API. If I type this “st.sidebar.date_input(‘start date’, datetime.date(2011,1,1))”, the code returns an error: descriptor ‘date’ requires a ‘datetime.datetime’ object but received a ‘int’.

Can someone help me out? :slight_smile:

Thanks!

Dear @madbaets! Welcome to the community! :blush:

I’m looking into this now and will get back to you!

Dear Adrien. Thanks for getting back to me so quickly. Appreciate your help! Looking forward to your solution :slight_smile:

Hi @madbaets:

I wasn’t able to reproduce your issue on my computer. This worked for me on both Python 2.7.10 and Python 3.6.3:

import streamlit as st
import datetime

date = st.sidebar.date_input('start date', datetime.date(2011,1,1))
st.write(date)

My suspicion is that this has something to do with your Python version. In order for us to help you further, could you please fill out a bug report. You don’t need to write too much. You can just refer to this post. :slight_smile: The most important part of the bug report is the bottom part about which version of everything you’re using.

Thanks for using Streamlit! :heart:

Hi Adrien!

I got it to work. I made a mistake when I imported the module datetime.
What I did was the following: From datetime import date, datetime.
=> When you import date as well, python is confused and messes up.

The answer thus lies into importing only the module datetime as a whole.

However, I’m still not able to make a slider with a range of dates, since the widget allows us to only use integers or floats as values for the slider. Do you happen to know if a datetime slider is on the roadmap?

Thanks!

1 Like

Hi @madbaets.

I’m happy you got it to work! :slight_smile:

Unfortunately, there’s currently no “date range widget,” but please feel free to submit a feature request. The more detail you can provide the better!

In the meantime, may I please suggest this workaround:

import streamlit as st
import datetime

today = datetime.date.today()
tomorrow = today + datetime.timedelta(days=1)
start_date = st.date_input('Start date', today)
end_date = st.date_input('End date', tomorrow)
if start_date < end_date:
    st.success('Start date: `%s`\n\nEnd date:`%s`' % (start_date, end_date))
else:
    st.error('Error: End date must fall after start date.')


3 Likes

Hi All,
I had started to explore Streamlit but these date pickers are there but how to choose date range and get the data fetched from the data-frame.

Hi @Anas_Riz -

From Datetime slider above, Adrien shows assigning the values start_date and end_date to variables. If you want to limit the data fetched from a dataframe, you can pass start_date and end_date as part of a pandas indexing operation. This StackOverflow example covers how to accomplish various date and datetime operations:

Best,
Randy

2 Likes

Hey, @Adrien_Treuille thanks for the workaround.
When I am changing the start date, the end date should also change, right?
But that is not the case here, when I start streamlit for the first time then it’s working as expected but when I am making the changes in the start date from the UI, the end date is not changing.

Thanks!

Hey there,

is there a way to reformat the calendar by weekdays? I wish it would be start with a monday on the first column (left) and end up with a lazy sunday on the last column (right)

PS: I love streamlit so much.

3 Likes

My take on the problem:

image

       import streamlit as st
       import datetime as dt
       import pandas as pd
       from dateutil.relativedelta import relativedelta # to add days or years


        ## Range selector
        cols1,_ = st.beta_columns((1,2)) # To make it narrower
        format = 'MMM DD, YYYY'  # format output
        start_date = dt.date(year=2021,month=1,day=1)-relativedelta(years=2)  #  I need some range in the past
        end_date = dt.datetime.now().date()-relativedelta(years=2)
        max_days = end_date-start_date
        
        slider = cols1.slider('Select date', min_value=start_date, value=end_date ,max_value=end_date, format=format)
        ## Sanity check
        st.table(pd.DataFrame([[start_date, slider, end_date]],
                      columns=['start',
                               'selected',
                               'end'],
                      index=['date']))
3 Likes

Hello, i use the methode 1 in the StackOverflow example to filtring dataframe by various date, but i have this message error :

Have you any idea for the cause of the issue ?

Please find below the code that i used :

df = ld.load_data_projet()

start_date = st.date_input('Date de début :')
end_date = st.date_input('Date de fin :')
if start_date < end_date:
    pass
else:
    st.error('Error: Date de fin doit être choisi après la dete de début.')

mask = (df['CREATEDDATE'] > start_date) & (df['CREATEDDATE'] <= end_date)
df = df.loc[mask]
# And display the result!
st.dataframe(df)

Thanks

Might I suggest that you need to compare a date value with a date value, in your case;

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

Should work now, as the return type from the st.date_input is a datetime.date.

2 Likes

Okay, now it definetely work, i tried this :

start_date, end_date = st.date_input('start date  - end date :', [])
        if start_date < end_date:
            pass
        else:
            st.error('Error: End date must fall after start date.')

mask = (df['CREATEDDATE'] > start_date) & (df['CREATEDDATE'] <= end_date)

An i get the dates input (start date and end date) in the same select box :

Tanks :slight_smile:

2 Likes

I Have this massage error when i tied your methode :

AttributeError: Can only use .dt accessor with datetimelike values

i think the type of date_input is in str (ex : “strartdate20210910”)