How do I parse a date as an argument with argparse?

Chase CB picture Chase CB · Jan 29, 2014 · Viewed 16.3k times · Source

Im trying to write a python program that I will run at the command line. I'd like the program to take a single input variable. Specifically, I would use a date in the form of 2014-01-28 (yyyy-mm-dd):

e.g. python my_script.py 2014-01-28

It seems argparse might be able to help me but I have found very little documentation regarding the module. Does anyone have experience with something like this?

Answer

mgilson picture mgilson · Jan 29, 2014

There's lots of documentation in the standard library, but generally, something like:

import argparse
import datetime

parser = argparse.ArgumentParser()
parser.add_argument('date', type=lambda s: datetime.datetime.strptime(s, '%Y-%m-%d'))
args = parser.parse_args(['2012-01-12'])  # For testing.  Pass no arguments in production
print args.date