Forms DateTime field


class DateTimeField( kwargs )

  • Default widget: DateTimeInput

  • Empty value: None

  • Normalizes to: A Python datetime.datetime object.

  • Validates that the given value is either a datetime.datetime, or string formatted in a particular datetime format.

  • Error message keys: required, invalid

class DateTimeField(BaseTemporalField):
    widget = DateTimeInput
    input_formats = formats.get_format_lazy('DATETIME_INPUT_FORMATS')
    default_error_messages = {
        'invalid': _('Enter a valid date/time.'),

    def prepare_value(self, value):
        if isinstance(value, datetime.datetime):
            value = to_current_timezone(value)
        return value

    def to_python(self, value):
        Validate that the input can be converted to a datetime. Return a
        Python datetime.datetime object.
        if value in self.empty_values:
            return None
        if isinstance(value, datetime.datetime):
            return from_current_timezone(value)
        if isinstance(value,
            result = datetime.datetime(value.year, value.month,
            return from_current_timezone(result)
        result = super().to_python(value)
        return from_current_timezone(result)

    def strptime(self, value, format):
        return datetime.datetime.strptime(value, format)


class DateTimeBaseInput(TextInput):
    format_key = ''
    supports_microseconds = False

    def __init__(self, attrs=None, format=None):
        self.format = format or None

    def format_value(self, value):
        return formats.localize_input(value, self.format or formats.get_format(self.format_key)[0])

class DateTimeInput(DateTimeBaseInput):
    format_key = 'DATETIME_INPUT_FORMATS'
    template_name = 'django/forms/widgets/datetime.html'


{% include "django/forms/widgets/input.html" %}


<input type="{{ widget.type }}" name="{{ }}"
{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %}
{% include "django/forms/widgets/attrs.html" %}>


{% for name, value in widget.attrs.items %}{% if value is not False %} {{ name }}
{% if value is not True %}="{{ value|stringformat:'s' }}"{% endif %}{% endif %}{% endfor %}


from django.utils.dateparse import parse_datetime
from django.utils.encoding import force_str

class ISODateTimeField(forms.DateTimeField):

    def strptime(self, value, format):
        return parse_datetime(force_str(value))