Skip to content

Instantly share code, notes, and snippets.

@monkut
Last active May 10, 2023 15:47
Show Gist options
  • Save monkut/e60eea811ef085a6540f to your computer and use it in GitHub Desktop.
Save monkut/e60eea811ef085a6540f to your computer and use it in GitHub Desktop.
Custom date/datetime type validators for python's argparse module
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)
@jmccormac01
Copy link

This worked really well for me today. I've modified it slightly to read in dates only. Thanks!

@alexus987
Copy link

alexus987 commented Oct 30, 2018

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

@J0E-E
Copy link

J0E-E commented Dec 17, 2021

Thank you for this. :) Super helpful.

@imranrazakhan
Copy link

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