Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a date as an argument with argparse?

Im trying to write a python program that I will run at the command line. I'd like the program to take a single input variable. Specifically, I would use a date in the form of 2014-01-28 (yyyy-mm-dd):

e.g. python my_script.py 2014-01-28

It seems argparse might be able to help me but I have found very little documentation regarding the module. Does anyone have experience with something like this?

like image 865
Chase CB Avatar asked Jan 29 '14 16:01

Chase CB


People also ask

How do you add an argument to a parser?

ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() . Some important parameters to note for this method are name , type , and required .

What is arg parsing?

argparse — parse the arguments. Using argparse is how you let the user of your program provide values for variables at runtime. It's a means of communication between the writer of a program and the user.

How does an argument parse work?

The argparse module makes it easy to write user-friendly command-line interfaces. It parses the defined arguments from the sys. argv . The argparse module also automatically generates help and usage messages, and issues errors when users give the program invalid arguments.


1 Answers

There's lots of documentation in the standard library, but generally, something like:

import argparse import datetime  parser = argparse.ArgumentParser() parser.add_argument(         'date',         type=lambda s: datetime.datetime.strptime(s, '%Y-%m-%d'), )  # For testing.  Pass no arguments in production args = parser.parse_args(['2012-01-12']) print(args.date) # prints datetime.datetime object 
like image 80
mgilson Avatar answered Oct 07 '22 01:10

mgilson