iPyWidget with date slider?

atkat12 picture atkat12 · Aug 31, 2016 · Viewed 11.7k times · Source

I am wondering if there's an easy way to build an iPyWidget with a datetime slider. Right now it is easy to slide over integer or floating point ranges (e.g. numbers 1-10, decimals 0.01, 0.02, ...).

I imagine you could convert dates to floats or integers, build some sort of slider using these, and then convert back to dates for the display labels on the slider. However, this seems clunky. Does anyone have a smoother solution?

Answer

fdorssers picture fdorssers · May 24, 2018

A general purpose range slider widget called SelectionRangeSlider has been added to ipywidgets in May 2017. This slider can be used for all sorts of data, including dates.

The code sample below creates a range slider allowing the user to select a date range between April 24 and May 24.

import ipywidgets as widgets
import pandas as pd
from datetime import datetime

start_date = datetime(2018, 4, 24)
end_date = datetime(2018, 5, 24)

dates = pd.date_range(start_date, end_date, freq='D')

options = [(date.strftime(' %d %b %Y '), date) for date in dates]
index = (0, len(options)-1)

selection_range_slider = widgets.SelectionRangeSlider(
    options=options,
    index=index,
    description='Dates',
    orientation='horizontal',
    layout={'width': '500px'}
)

selection_range_slider

Date range slider with full month selection

Date range slider with partial month selection

This slider can easily be combined with the interact functionality from ipywidgets. In that case the widget returns a tuple consisting of the selected upper and lower range.

def print_date_range(date_range):
    print(date_range)

widgets.interact(
    print_date_range,
    date_range=selection_range_slider
);

The two outputs for the previously selected ranges:

(Timestamp('2018-04-24 00:00:00', freq='D'), Timestamp('2018-05-24 00:00:00', freq='D'))
(Timestamp('2018-04-30 00:00:00', freq='D'), Timestamp('2018-05-18 00:00:00', freq='D'))