Dash Range Slider with date

I want to create a range slider from Jan 2018- Jan 2019. I have a column df[‘AUDITTIME’] where the date is a timestamp in this format 2019-01-04 14:00. What I need is a min Value of Jan 2018 and Max value of Jan 2019 and the range slider will be updated if the user what to narrow the month range. So I need the min, max value for the callback.
The problem is that the values is only a number so I do not know how to convert them and how to implement the marks.

3 Likes

@kkayee123,
Firstly, I am a little confused with your question - Do you want the minimum timestamp of January-2018 and the Maximum timestamp of January-2019? Or do you want the minimum and maximum timestamps of your data-set from the columns AUDITTIME? I’ll try to answer from both assumptions.

For the First One, if you have pandas imported, you can generate the minimum timestamp of Jan-2018 as pandas.Timestamp(2018, 1, 1, 0), and similarly the max timestamp of Jan-2019 as pandas.Timestamp(2019, 1, 31, 23, 59, 59). On the python interpreter it looks like Timestamp('2018-01-01 00:00:00') and Timestamp('2018-12-31 23:59:59') respectively.

For the Second one, you can again simply use pandas and pass the arguments to dcc.Slider() like so - dcc.Slider(min=df['AUDITTIME'].min().day, max=df['AUDITTIME'].max().day, value=df['AUDITTIME'].min().day, marks = {date.day:date.day for date in df['AUDITTIME'].dt.date.unique()})

I hope I answered you. Please let me know if not.

1 Like

I want the minimum and maximum from the colum Audittime but the min woul be Jan18 and max Jan19. I want the range slider to show every month and year from jAN18 to now. The range slider you have created is based only on date and not on month/year basis.

I want every month to be displayed JAN18, Feb18, Marz18…, Dec18,Jan19

Hi metallica, I am facing almost a similar problem. I have a date column (in yyyy-mm-dd format). I want to have the slider in bubble chart based on date (not by year or day). For other two line charts x axis will be date as well. All dates in yyyy-mm-dd format. I tried this (below) but the layout is not loading.

html.Div(dcc.Slider(
id=‘crossfilter-year–slider’,
min=pd.to_datetime(df[‘MyDate’]).dt.date.min(),
max=pd.to_datetime(df[‘MyDate’]).dt.date.max(),
value=pd.to_datetime(df[‘MyDate’]).dt.date.max(),
marks = {date:date for date in pd.to_datetime(df[‘MyDate’]).dt.date.unique()}

def create_time_series(dff, axis_type, title):
return {
‘data’: [go.Scatter(
#x=dff[‘Year’],
x=pd.to_datetime(dff[‘MyDate’]).dt.date, <-- I think it’s throwing error here

I also want to group the bubbles and add legend…(later).

Appreciate any help or hint. Thank you.

I’m also having the same trouble. People keep suggesting to convert Pandas datetime series into numeric values (Date range slider) though this is not fixing the underlying question many people have…how to use Pandas datetimes with dash. Any suggestions out there aside from converting to integer or using epochs ([Solved] Has Anyone Made a Date-Range-Slider?)?

Maybe this will help:

I used a combination of a DateRangePicker and RangeSlider object where the RangeSlider resembles the amount of unique occurrences in the pandas TimeStamp range, sorted by date. I did not add any values on the RangeSlider object for now but you could show the dates/month by using the index number presented in the RangeSlider to index the Pandas TimeStamp Series.

 dcc.DatePickerRange(
                            id='datepickerrange',
                            start_date=df['Date'].min().date(),
                            end_date=df['Date'].max().date(),
                            min_date_allowed=df['Date'].min().date(),
                            max_date_allowed=df['Date'].max().date(),
                            display_format='D MMM YYYY'
                            ),
              
dcc.RangeSlider(
                            id='rangeslider',
                            min=0,
                            max=df['Date'].nunique()-1,
                            value=[0, df['Date'].nunique()-1],
                            allowCross=False
                            )

@app.callback(Output('datepickerrange', 'start_date'), 
                       [Input('df', 'children'),
                        Input('rangeslider', 'value')])
def update_daterangestart(df, rangeslider_value):
    df= pd.read_json(sorties, orient='split')
    return np.sort(df['Date'].dt.date.unique())[rangeslider_value[0]]

@app.callback(Output('top10-datepickerrange', 'end_date'), 
                       [Input('df', 'children'),
                        Input('top10-rangeslider', 'value')])
def update_daterangeend(df, rangeslider_value):
    df = pd.read_json(sorties, orient='split')
    return np.sort(df['Date'].dt.date.unique())[rangeslider_value[1]]

Here, my DataFrame df is stored as a hidden div: html.Div(id=‘df’, style={‘display’: ‘none’}, children=df.to_json(date_format=‘iso’, orient=‘split’))

I still want to add the function to also update the position of the RangeSlider once the DatePicker is changed but this normally causes a never-ending loop of updates. Therefore I need to add the no update function once the value is the same as it was before: I want to create a conditional callback in dash, is it possible?. But if anyone already managed to do so, please let me know!

How about something like

marks={int(i):str(j) for i,j in zip(range(len(df.years)),df[“years”])}
And then you can mimic the same in the functional callbacks to update the values by dictionary keys

I used this:


#transform every unique date to a number
numdate= [x for x in range(len(df['DATE'].unique()))]

#then in the Slider
dcc.Slider(min=numdate[0], #the first date
               max=numdate[-1], #the last date
               value=numdate[0], #default: the first
               marks = {numd:date.strftime('%d/%m') for numd,date in zip(numdate, df['DATE'].dt.date.unique())})
])

#in marks I assigned every numeric date to the actual df’s date, in that way, the date is displayed in dash