Specify date format for Python argparse input arguments

Per the documentation:

The type keyword argument of add_argument() allows any necessary type-checking and type conversions to be performed … The argument to type can be any callable that accepts a single string.

You could do something like:

def valid_date(s):
    try:
        return datetime.strptime(s, "%Y-%m-%d")
    except ValueError:
        msg = "not a valid date: {0!r}".format(s)
        raise argparse.ArgumentTypeError(msg)

Then use that as type:

parser.add_argument(
    "-s", 
    "--startdate", 
    help="The Start Date - format YYYY-MM-DD", 
    required=True, 
    type=valid_date
)

Leave a Comment