Skip to main content

DateTimeField

This class provides a field for handling date and time input, ensuring data is validated and converted into Python datetime objects. It supports various input formats and automatically manages timezone conversions to ensure consistency across different locales. The field also integrates with specific widgets and error handling mechanisms to process temporal data effectively.

Attributes

AttributeTypeDescription
widget[Widget](../widgets/widget.md?sid=django_forms_widgets_widget) = DateTimeInputThe default widget class used to render this field on an HTML form.
input_formatsiterable = DateTimeFormatsIterator()An iterable of formats used to attempt to convert a string into a valid datetime.datetime object.
default_error_messagesdict = {"invalid": "Enter a valid date/time."}A dictionary containing the default error message for invalid date or time inputs.

Methods


prepare_value()

@classmethod
def prepare_value(
value: any
) - > datetime.datetime

Converts the given value into a format suitable for display in a widget, ensuring datetime objects are localized to the current timezone.

Parameters

NameTypeDescription
valueanyThe raw data value to be prepared for widget display

Returns

TypeDescription
datetime.datetimeThe localized datetime object or the original value if it is not a datetime instance

to_python()

@classmethod
def to_python(
value: any
) - > datetime.datetime

Validate that the input can be converted to a datetime. Return a Python datetime.datetime object.

Parameters

NameTypeDescription
valueanyThe input value to validate and convert, which can be a string, date, or datetime object

Returns

TypeDescription
datetime.datetimeA Python datetime object localized to the current timezone, or None if the input is empty

strptime()

@classmethod
def strptime(
value: string,
format: string
) - > datetime.datetime

Parses a string representation of a date and time into a datetime object using a specific format string.

Parameters

NameTypeDescription
valuestringThe string representation of the date and time to be parsed
formatstringThe strftime-style format string used to interpret the input value

Returns

TypeDescription
datetime.datetimeThe datetime object resulting from parsing the input string