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

PythonDateCommand LineArgparse

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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'),
)

# For testing.  Pass no arguments in production
args = parser.parse_args(['2012-01-12'])
print(args.date) # prints datetime.datetime object

Solution 2 - Python

As of Python 3.7, a (marginally) more convenient option is fromisoformat: https://docs.python.org/3/library/datetime.html#datetime.date.fromisoformat

Using it, you can replace the relevant line in mgilson's code with this:

parser.add_argument('date', type=datetime.date.fromisoformat)

(I would also add a help argument to this invocation of add_argument, and mention that the input should be in ISO format.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChase CBView Question on Stackoverflow
Solution 1 - PythonmgilsonView Answer on Stackoverflow
Solution 2 - PythonDamienView Answer on Stackoverflow