worse date converter

"Matthew Wilson" <[email protected]> Sat, 6 Sep 2008 20:45:34 -0400
Newsgroups gmane.comp.python.formencode
Message-ID <[email protected]>
Hi, I needed a way to convert some strings into dates, but the strings
wouldn't be in the formats acceptable to the current dateconverter
validator.

Originally, I tried looking into the dateconverter so I could add
another date format that it could support, but then I got scared by
those enormous regular expressions and decided to go with this
approach.  Anyhow, feedback is welcome.

from time import strptime
from formencode import Invalid
from formencode.validators import FancyValidator

class WorseDateConverter(FancyValidator):

    """
    Requires a list of valid date format strings.

    ::

        >>> wdc = WorseDateConverter(['%m-%d-%Y',  '%m/%d/%Y', '%Y-%m-%d'])
        >>> wdc.to_python('09-06-2008')
        datetime.date(2008, 9, 6)
        >>> wdc.to_python('09/06/2008')
        datetime.date(2008, 9, 6)
        >>> wdc.to_python('2008-09-06')
        datetime.date(2008, 9, 6)
        >>> wdc.to_python('2008/09/06') # slashes instead of dashes.
        Traceback (most recent call last):
            ...
        Invalid: I couldn't parse 2008/09/06 with any of my formats!
    """

    def __init__(self, dateformats):
        self.dateformats = dateformats

    def to_python(self, value, state=None):

        for datefmt in self.dateformats:

            try:
                tt = strptime(value, datefmt)
                return date(tt.tm_year, tt.tm_mon, tt.tm_mday)

            except ValueError:
                pass

        else:
            msg = ("I couldn't parse %s with any of my formats!"
                % (value))

            raise Invalid(msg, value, state)

    def from_python(self, value, state=None):
        return value.strftime(self.datefmt)


-- 
Matthew Wilson
[email protected]
http://tplus1.com
216-470-6058

-------------------------------------------------------------------------
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/