Receive date type (datetime) with ArgumentParser [python]

Introduction

A reminder of how to receive a datetime.date type value as an optional argument in python.

Thing you want to do

--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.

Specify the datetime type with ArgumentParser

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

Customize the error message

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.

The type of exception to be processed (ValueError) was actually generated and confirmed.
>>> 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

in conclusion

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.

References

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

Receive date type (datetime) with ArgumentParser [python]
Get date with python
Extract "current date only" and "current date and time" with python datetime.
0 Convert unfilled date to datetime type with regular expression
python> datetime> From date string (ISO format: 2015-12-09 12:40:08) to datetime type
Scikit-learn DecisionTreeClassifier with datetime type values
How to calculate date with python
Master the type with Python [Python 3.9 compatible]
Conversion of string <-> date (date, datetime) in Python
Receive textual data from mysql with python
[Python] Easy argument type check with dataclass
POST variously with Python and receive with Flask
FizzBuzz with Python3
Scraping with Python
Python date arithmetic
[Python] Create a list of date and time (datetime type) for a certain period
Python numeric type
Convert "number" of excel date to python datetime
Statistics with python
Scraping with Python
Python with Go
Integrate with Python
Convert Windows epoch values to date with python
Check the date of the flag duty with Python
AES256 with python
Tested with Python
python starts with ()
with syntax (Python)
[Python3] Read and write with datetime isoformat with json
Bingo with python
Zundokokiyoshi with python
Python2 string type
Python # string type
How to handle datetime type in python sqlite3
[Python] Class type and usage of datetime module
[Python] Determine the type of iris with SVM
[Python] How to compare datetime with timezone added
Excel with Python
Microcomputer with Python
Cast with python
[Python] Convert time display (str type) using "" "and"'" to seconds (float type) with datetime and timedelta
Simulate a good Christmas date with a Python optimized model
[python] Create a date array with arbitrary increments with np.arange
Find this week's date in any format with python
Summary of date processing in Python (datetime and dateutil)
Serial communication with Python
Zip, unzip with python
Primality test with Python
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Scraping with Python (preparation)
Try scraping with Python.
Sequential search with Python
"Object-oriented" learning with python
Run Python with VBA
Solve AtCoder 167 with python
Serial communication with python
[Python] Use JSON with Python
Learn Python with ChemTHEATER
Run prepDE.py with python3