Exemple #1
0
class DateTimeField(Field):
    """
    A text field which stores a `datetime.datetime` matching a format.
    """

    widget = widgets.DateTimeInput()

    def __init__(self,
                 label=None,
                 validators=None,
                 format="%Y-%m-%d %H:%M:%S",
                 **kwargs):
        super().__init__(label, validators, **kwargs)
        self.format = format
        self.strptime_format = clean_datetime_format_for_strptime(format)

    def _value(self):
        if self.raw_data:
            return " ".join(self.raw_data)
        return self.data and self.data.strftime(self.format) or ""

    def process_formdata(self, valuelist):
        if not valuelist:
            return

        date_str = " ".join(valuelist)
        try:
            self.data = datetime.datetime.strptime(date_str,
                                                   self.strptime_format)
        except ValueError as exc:
            self.data = None
            raise ValueError(
                self.gettext("Not a valid datetime value.")) from exc
Exemple #2
0
class DateTimeField(Field):
    """
    A text field which stores a :class:`datetime.datetime` matching one or
    several formats. If ``format`` is a list, any input value matching any
    format will be accepted, and the first format in the list will be used
    to produce HTML values.
    """

    widget = widgets.DateTimeInput()

    def __init__(self,
                 label=None,
                 validators=None,
                 format="%Y-%m-%d %H:%M:%S",
                 **kwargs):
        super().__init__(label, validators, **kwargs)
        self.format = format if isinstance(format, list) else [format]
        self.strptime_format = clean_datetime_format_for_strptime(self.format)

    def _value(self):
        if self.raw_data:
            return " ".join(self.raw_data)
        return self.data and self.data.strftime(self.format[0]) or ""

    def process_formdata(self, valuelist):
        if not valuelist:
            return

        date_str = " ".join(valuelist)
        for format in self.strptime_format:
            try:
                self.data = datetime.datetime.strptime(date_str, format)
                return
            except ValueError:
                self.data = None

        raise ValueError(self.gettext("Not a valid datetime value."))