Skip to content

Instantly share code, notes, and snippets.

@thanos
Created July 5, 2011 14:41
Show Gist options
  • Select an option

  • Save thanos/1064956 to your computer and use it in GitHub Desktop.

Select an option

Save thanos/1064956 to your computer and use it in GitHub Desktop.
Extending python's optparser to handle datetime types
import datetime, copy
from optparse import Option, OptionValueError
def check_datatime(option, opt, value):
try:
return datetime.datetime.strptime(value, option.datetime_format)
except ValueError:
raise OptionValueError(
"option %s: invalid complex value: %r" % (opt, value))
class ExtendedOption (Option):
TYPES = Option.TYPES + ("datetime",)
TYPE_CHECKER = copy(Option.TYPE_CHECKER)
TYPE_CHECKER["datatime"] = check_datatime
ATTRS = copy(Option.ATTRS) + ["datatime_format",]
datetime_format = '%Y-%m-%d'
def make_option(*args, **kwa):
return ExtendedOption(*args, **kwa)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment