Specify the format of input arguments argparse python

I have a python script that requires input of several commands and I use argparse to parse them. I found the documentation a bit confusing and could not find a way to check the format in the input parameters. What I mean by format validation is explained using this sample script:

parser.add_argument('-s', "--startdate", help="The Start Date - format YYYY-MM-DD ", required=True) parser.add_argument('-e', "--enddate", help="The End Date format YYYY-MM-DD (Inclusive)", required=True) parser.add_argument('-a', "--accountid", type=int, help='Account ID for the account for which data is required (Default: 570)') parser.add_argument('-o', "--outputpath", help='Directory where output needs to be stored (Default: ' + os.path.dirname(os.path.abspath(__file__))) 

I need to check for the -s and -e options that the user input is in the format YYYY-MM-DD . Is there an option in argparse that I don't know about what this does.

+46
python argparse
Aug 24 '14 at 10:41
source share
2 answers

Per documentation :

The type argument of the add_argument() keyword allows any necessary type checks and type conversions ... type= can accept any invoked calls that take a single string argument and return a converted value

You can do something like:

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

Then use this as type :

 parser.add_argument("-s", "--startdate", help="The Start Date - format YYYY-MM-DD", required=True, type=valid_date) 
+126
Aug 24 '14 at 10:53 on
source share

To add to the answer above, you can use the lambda function if you want to store it in a single line. For example:

 parser.add_argument('--date', type=lambda d: datetime.strptime(d, '%Y%m%d')) 

Old thread, but the question was still relevant for me!

+20
Oct 17 '16 at 20:48
source share



All Articles