Ticket #4428: datetimefield_millisecond.patch

File datetimefield_millisecond.patch, 2.3 KB (added by berto, 17 years ago)
  • fields.py

     
    271271    '%m/%d/%y',              # '10/25/06'
    272272)
    273273
     274
     275def timeparse(t, format):
     276    """Parse a time string that might contain fractions of a second.
     277     
     278    Fractional seconds are supported using a fragile, miserable hack.
     279    Given a time string like '02:03:04.234234' and a format string of
     280    '%H:%M:%S', time.strptime() will raise a ValueError with this
     281    message: 'unconverted data remains: .234234'. If %S is in the
     282    format string and the ValueError matches as above, a datetime
     283    object will be created from the part that matches and the
     284    microseconds in the time string.
     285     
     286    Found at: http://www.thescripts.com/forum/thread506538.html
     287    """
     288   
     289    try:
     290        return datetime.datetime(*time.strptime(t, format)[0:6])
     291    except ValueError, msg:
     292        if "%S" in format:
     293            msg = str(msg)
     294            regex_types = (
     295                r"unconverted data remains: \.([0-9]{1,6})$",
     296                r"unconverted data remains: \,([0-9]{3,3})$"
     297            )
     298           
     299            for regex in regex_types:
     300                mat = re.match(regex, msg)
     301
     302                if mat is not None:
     303                    # fractional seconds are present - this is the style
     304                    # used by datetime's isoformat() method
     305                    frac = "." + mat.group(1)
     306                    t = t[:-len(frac)]
     307                    t = datetime.datetime(*time.strptime(t, format)[0:6])
     308                    microsecond = int(float(frac)*1e6)
     309                    return t.replace(microsecond=microsecond)
     310        raise
     311
    274312class DateTimeField(Field):
    275313    def __init__(self, input_formats=None, *args, **kwargs):
    276314        super(DateTimeField, self).__init__(*args, **kwargs)
     
    290328            return datetime.datetime(value.year, value.month, value.day)
    291329        for format in self.input_formats:
    292330            try:
    293                 return datetime.datetime(*time.strptime(value, format)[:6])
     331                return timeparse(value, format)
    294332            except ValueError:
    295333                continue
    296334        raise ValidationError(gettext(u'Enter a valid date/time.'))
Back to Top