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)
@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