A reminder of how to receive a datetime.date type value as an optional argument in python.
--Receives a date string (eg 2020-01-01
) as an optional argument and converts it to datetime.date type.
--Original error message is issued when a malformed character string is passed.
For the basic usage of Argparse, Official Tutorial was helpful. In the tutorial, the int type is specified, but this time I want to specify the datetime.date type.
Define a function date_type
that converts a date string (eg 2020-01-01
) to a date object and specify it in the type of ArgumentParser.
test.py
import argparse
import datetime
# str ->date type conversion function
def date_type(date_str):
return datetime.date.fromisoformat(date_str)
if __name__ == '__main__':
#Get ArgumentParser
arg_parser = argparse.ArgumentParser()
#Definition of date specification options
arg_parser.add_argument("-d", "--date",
help="Date must be in ISO format. For example: 2020-01-01.",
type=date_type)
#Get optional arguments
args = arg_parser.parse_args()
date = args.date
print(date.year,date.month,date.day)
Execution result
>python test.py -d 2020-01-01
2020 1 1
In the above code, if the optional argument is in a format other than the ISO format date, the following error will be output.
>python test.py -d hoge
usage: mtg.py [-h] [-d DATE]
mtg.py: error: argument -d/--date: invalid date_type value: 'hoge'
I don't like the defined function name date_type being included in the error message, so customize the error content.
Modify the type conversion function date_type
as follows.
def date_type(date_str):
try:
return datetime.date.fromisoformat(date_str)
except ValueError as e:
raise argparse.ArgumentTypeError(str(e) + " Date must be in ISO format. ex. 2020-01-01")
Try-except is raising a new exception.
>>> import datetime
>>> datetime.date.fromisoformat('hoge')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Invalid isoformat string: 'hoge'
Execution result
>python test.py -d hoge
usage: test.py [-h] [-d DATE]
test.py: error: argument -d/--date: Invalid isoformat string: 'hoge' Date must be in ISO format. ex. 2020-01-01
At first I googled with python argparser datetime
, but I didn't find any Japanese literature because it was too cornered in the jubako, so I made an article.
Official Argparser Tutorial: Argparse Tutorial — Python 3.8.2 Documentation
I also referred to @ kzkadc's article: bow: [A brief summary of how to use ArgumentParser --Qiita](https://qiita.com/kzkadc/items/e4fc7bc9c003de1eb6d0#%E5%9E%8B%E6%8C%87%E5%AE%9A%E3%81% 97% E3% 81% 9F% E3% 81% 84)
Official documentation [argparse ---command line options, arguments, subcommand parsers — Python 3 \ .8 \ .2 documentation](https://docs.python.org/ja/3/library/argparse.html# type)
Recommended Posts