2

I'm new using Python 2.6

I'm trying to pass a date as argument with Optargs.

When tryin to do like this : Specify format for input arguments argparse python I get this error :

parser.add_option('-e', '--end', help='end date - format YYYYMMDD', type=valid_date)

File "/usr/lib64/python2.6/optparse.py", line 1012, in add_option
option = self.option_class(*args, **kwargs)
File "/usr/lib64/python2.6/optparse.py", line 577, in __init__
checker(self)
File "/usr/lib64/python2.6/optparse.py", line 660, in _check_type
raise OptionError("invalid option type: %r" % self.type, self)
optparse.OptionError: option -e/--end: invalid option type: <function valid_date at 0x7f310294fde8>

My program is like this:

parser.add_option('-e', '--end', help='end date - format YYYYMMDD', type=valid_date)

(...)

def valid_date(s):
  try:
    return datetime.datetime.strptime(s, "%Y%m%d")
  except ValueError:
     print("Not a valid date: '{0}'.".format(s))

Could you please help me ?

Thank you!

Community
  • 1
  • 1
ali
  • 115
  • 10
  • According to the link you referenced, they are using `ArgumentParser`. And since `optparse` is deprecated you should use `argparse` – ham Sep 21 '16 at 10:15
  • But for python 2.6 isn't it better to use optparse? – ali Sep 21 '16 at 11:29

2 Answers2

5

If you need to stick to python 2.6, here is an implementation with optparse:

from optparse import Option, OptionValueError, OptionParser
from copy import copy
from datetime import datetime

# function to check/convert option value to datetime object
def valid_date(option, opt, value):
    try:
        return datetime.strptime(value,'%Y%m%d')
    except ValueError:
        raise OptionValueError( 'option %s: invalid date format: %r' % (opt, value))

# extend Option class with date type
class MyOption(Option):
    TYPES = Option.TYPES + ('date',)
    TYPE_CHECKER = copy(Option.TYPE_CHECKER)
    TYPE_CHECKER['date'] = valid_date

# parse options     
parser = OptionParser(option_class=MyOption)
parser.add_option( '-e', '--end', type='date' , help='end date - format YYYYMMDD')
(opts, args) = parser.parse_args()

# do something meaningful
print opts.end

For further details see https://docs.python.org/2/library/optparse.html#adding-new-types

Hauke
  • 242
  • 2
  • 10
0

If your python >=2.7, you can try argparse,

def valid_date(value):
    return datetime.strptime(value,'%Y%m%d')

parser = argparse.ArgumentParser()
parser.add_argument('--end', dest='d', required=True, type=valid_date)
马哥私房菜
  • 903
  • 6
  • 4