Search code examples
pythonpython-click

How to use click.prompt to get a valid date from the user?


Hello,

I'm actually learning how to use some elements from the click package, and I'd like to be able to get a valid date from the user by using the promptcommand.

I tried to look up the docs, and I found this under http://click.pocoo.org/5/prompts/:

To manually ask for user input, you can use the prompt() function. By default, it accepts any Unicode string, but you can ask for any other type.

So I wrote this code and tried to pass the class datetime.datetime as the wanted type of input:

import datetime

value = click.prompt("Enter a date", type=datetime.datetime)

when I execute this code the prompt appears, but after I insert a valid date and press the enter key I'm getting this error message:

Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/click/termui.py", line 98, in prompt result = value_proc(value) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/click/types.py", line 38, in call return self.convert(value, param, ctx) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/click/types.py", line 87, in convert return self.func(value) TypeError: an integer is required (got type str)

Please, could you show me what am I doing wrong in this code ?

Basically I'd like to get a date value properly formatted by writing something like this piece of (partially imaginary) code:

import datetime

value = click.prompt("Enter a date", 
                     type=datetime.datetime,
                     format="%d/%m/%Y",
                     default=datetime.datetime.now())

Thank you very much


Solution

  • It doesn't seem that Click handles dates now, but it is probably something that may change in the future.

    Instead you could pass a parser with the value_proc parameter. I've used dateutil, but you can change it to datetime if you prefer it:

    from dateutil import parser
    import click
    
    def parse(value):
        try:
            date = parser.parse(value)
        except:
            raise click.BadParameter("Couldn't understand date.", param=value)
        return value
    
    value = click.prompt("Enter a date", value_proc=parse)