custom DatePicker in ipywidgets

Viewed 2145

I am using a DatePicker widget for selecting dates based on which I have to do some tasks in Jupyter notebook procedures. The DatePicker widget is created using ipywidget library.

The problem which I am facing now is that it shows all the dates of month and years.

Is there any way by which I can disable the dates which are not present in a list containing all the valid dates for my application.

For instance lets say I have a list of dates which has 2018-12-25, 2019-01-09 and 2019-01-13. So now, I want only these days to be enabled in the DatePicker widget and rest of the dates should be disabled.

Please suggest and help.!!!

1 Answers

Behind the scenes it uses a html date input which can only be limited to min and max dates apparently. See here.

That was enough for my use case, but I couldn't find anything in the offical documentation that helped. I did find a hack around the issue by using javascript to set the min and max tags on the generated html input box:

%matplotlib widget

import ipywidgets as widgets
from IPython.display import display, Javascript

date_picker = widgets.DatePicker(
    description='Pick a Date',
    disabled=False,
)
date_picker.add_class("start-date")

script = Javascript("\
                const query = '.start-date > input:first-of-type'; \
                document.querySelector(query).setAttribute('min', '2020-12-01'); \
                document.querySelector(query).setAttribute('max', '2021-01-01'); \
        ")

display(date_picker)
display(script)

which generates a widget with the correct html tags to limit the user input:

<div class="lm-Widget p-Widget jupyter-widgets widget-inline-hbox widget-datepicker start-date">
    <label class="widget-label" style="" title="Pick a Date" for="26e68439-2334-4335-93e2-9d9903607aab">Pick a Date</label>
    <input type="date" id="26e68439-2334-4335-93e2-9d9903607aab" min="2020-12-01" max="2021-01-01">
</div>
Related