95

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?

2 Answers 2

132

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
Sign up to request clarification or add additional context in comments.

7 Comments

basically i could replace args with sys.argv[1]?
@ChaseCB -- If you pass a list to parse_args, it will be used as if those arguments were passed on the command line. Under normal circumstances (if you don't pass anything) argparse uses sys.argv[1:]. See docs.python.org/dev/library/…
parser.parse_args('this is a test string'.split()) is another test option. It's equivalent to parse_args(['this','is',...]), and in a few edge conditions better.
@hpaulj -- better? I can't think of any way that it's better unless your argument is "it saves you some typing"...
I must have been mis-remembering how choices are best defined. The real reason I favor split is it can save typing. shlex.split would be a better choice if I wanted to simulate how the shell creates sys.argv
|
117

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

2 Comments

To get both date and time use parser.add_argument('date', type=datetime.datetime.fromisoformat, help='ISOformat - YYYY-MM-DD:HH:mm:ss')
"date" usually doesn't include a time of day. Additionally, the OP didn't ask for the time of day. And your format has ":" in the middle where a "T" goes in 8601.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.