5

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.!!!

Mayank Shekhar
  • 91
  • 1
  • 3
  • 8
  • If you only want to allow a few dates (up to, perhaps, a couple of dozen), a drop-down list seems like a better user experience. – cco Jan 14 '19 at 05:38
  • Thank you for the suggestion, but the date list which I have could have dates ranging from months to years. And also this list of dates gets generated dynamically, depending upon other user's selections. Considering this, I think having the dates disabled and enabled in the widget is the only option which I have. – Mayank Shekhar Jan 14 '19 at 05:51
  • 1
    I don't think the current DatePicker implementation has functionality to disable dates from being input. One alternative would be for your DatePicker instance to observe a function that would check the date value chosen against a list of acceptable dates, and return the DatePicker widget value to `None` if the chosen date is not in the list of allowed values. – ac24 Jan 14 '19 at 12:02

1 Answers1

0

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>
Statue26
  • 373
  • 1
  • 3
  • 10