Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a date using argparse in Python 3.7+?

parser.add_argument("-s", "--start-date", dest="start_date", 
                    default=date.today() - timedelta(days = 1), 
                    type=date, help="Date in the format yyyymmdd")

This method gives the error

argument_test.py: error: argument -s/--start-date: invalid date value: 20181215

I assume that argument received is a string and it is incompatible as the object expected is date. So, how do I actually pass the date object? Is there a work around?

I could parse a string and pass it to a date object. But, I'd like to explore other direct options.

like image 655
Tarun Maganti Avatar asked Oct 26 '25 04:10

Tarun Maganti


1 Answers

You can use a wrapper function that uses datetime.strptime to parse the given date string with the desired format:

parser.add_argument("-s", "--start-date", dest="start_date", 
                    default=date.today() - timedelta(days = 1), 
                    type=lambda d: datetime.strptime(d, '%Y%m%d').date(),
                    help="Date in the format yyyymmdd")
like image 116
blhsing Avatar answered Oct 28 '25 17:10

blhsing