Last active
May 10, 2023 15:47
-
-
Save monkut/e60eea811ef085a6540f to your computer and use it in GitHub Desktop.
Custom date/datetime type validators for python's argparse module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def valid_date_type(arg_date_str): | |
"""custom argparse *date* type for user dates values given from the command line""" | |
try: | |
return datetime.datetime.strptime(arg_date_str, "%Y-%m-%d") | |
except ValueError: | |
msg = "Given Date ({0}) not valid! Expected format, YYYY-MM-DD!".format(arg_date_str) | |
raise argparse.ArgumentTypeError(msg) | |
def valid_datetime_type(arg_datetime_str): | |
"""custom argparse type for user datetime values given from the command line""" | |
try: | |
return datetime.datetime.strptime(arg_datetime_str, "%Y-%m-%d %H:%M") | |
except ValueError: | |
msg = "Given Datetime ({0}) not valid! Expected format, 'YYYY-MM-DD HH:mm'!".format(arg_datetime_str) | |
raise argparse.ArgumentTypeError(msg) | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser(description='Example of custom type usage') | |
parser.add_argument('-s', '--start-datetime', | |
dest='start_datetime', | |
type=valid_datetime_type, | |
default=None, | |
required=True, | |
help='start datetime in format "YYYY-MM-DD HH:mm"') | |
args = parser.parse_args() | |
start_datetime_object = args.start_datetime | |
print(start_datetime_object) |
Thank you for this. :) Super helpful.
From python 3.7 you can use following two options
For date:
parser.add_argument('--date', type=datetime.date.fromisoformat, help='ISO format - YYYY-MM-DD')
parser.add_argument('--date', type=datetime.datetime.fromisoformat, help='ISOformat - YYYY-MM-DD:HH:mm:ss')
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AttributeError: 'module' object has no attribute 'parser'
Maybe before it was working, but now you should use
parser = argparse.ArgumentParser(description='Example of custom type usage')
Reference:
https://docs.python.org/3/library/argparse.html