Search code examples
pythonjupyteripywidgets

ipywidgets floatrangeslider daterangeslider


I tried to use FloatRangeSlider from ipywidgets in a jupyter-notebook such that the date is displayed:

import ipywidgets as widgets
from datetime import datetime

class myd:
    def __init__(self, value_datetime):
        self.value = value_datetime
    def __float__(self):
        return float(self.value.strftime("%s"))
    def __format__(self, format_spec):
        return self.value.strftime("%d.%m.%Y")

# Test
start = myd(datetime(2017,1,1))
end = myd(datetime(2017,10,1))
print(float(start), "{:.1f}".format(start))
print(float(end), "{:.1f}".format(end))

which correctly prints

1483225200.0 01.01.2017
1506808800.0 01.10.2017

However, the slider doesn't display as supposed:

widgets.FloatRangeSlider(
    value=[start, end],
    min=start,
    max=end,
    step=100,
    description='Test:',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    readout=True,
    readout_format='.1f',
)

It displays

Image of slider

but should display 01.01.2017 - 01.10.2017.

Thanks for any help.


Solution

  • It's nonsense to use a FloatRangeSlider, better use SelectionRangeSlider for some DataFrame df:

    import ipywidgets as widgets
    
    # create slider
    dates = list(pd.date_range(df.zeit.min(), df.zeit.max(), freq='D'))
    options = [(i.strftime('%d.%m.%Y'), i) for i in dates]
    index = (0, len(dates)-1)
    myslider = widgets.SelectionRangeSlider(
        options = options,
        index = index,
        description = 'Test',
        orientation = 'horizontal',
        layout={'width': '500px'}
    )
    
    def update_source(df, start, end):
        x = df[(df.zeit >= start) & (df.zeit < end)]
        #data = pd.DataFrame(x.groupby('who')['bytes'].sum())
        #data.sort_values(by="bytes", inplace=True)
        #data.reset_index(inplace=True)
        #return data
        return x
    
    def gui(model, bars):
        def myupdate(control1):
            start = control1[0].date()
            end = control1[1].date()
            #display(update_source(model, start, end).head(4))
            data = update_source(model, start, end)
        return myupdate
    
    widgets.interactive(gui(df, x), control1 = myslider)