How to parse a date as an argument using argparse?

I am trying to write a python program that I will run on the command line. I want the program to take one input variable. In particular, I would use a date in the form 2014-01-28 (yyyy-mm-dd):

eg. python my_script.py 2014-01-28

It seems that argparse can help me, but I have found very little documentation regarding the module. Does anyone have experience with something like this?

+4
source share
1 answer

There is documentation in the standard library , but usually something like:

import argparse
import datetime

parser = argparse.ArgumentParser()
parser.add_argument('date', type=lambda s: datetime.datetime.strptime(s, '%Y-%m-%d'))
args = parser.parse_args(['2012-01-12'])  # For testing.  Pass no arguments in production
print args.date
+10
source

Source: https://habr.com/ru/post/1524326/


All Articles