Created
July 5, 2011 14:41
-
-
Save thanos/1064956 to your computer and use it in GitHub Desktop.
Extending python's optparser to handle datetime types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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