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
| Attribute | Type | Description |
|---|---|---|
| widget | [Widget](../widgets/widget.md?sid=django_forms_widgets_widget) = DateTimeInput | The default widget class used to render this field on an HTML form. |
| input_formats | iterable = DateTimeFormatsIterator() | An iterable of formats used to attempt to convert a string into a valid datetime.datetime object. |
| default_error_messages | dict = {"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
| Name | Type | Description |
|---|---|---|
| value | any | The raw data value to be prepared for widget display |
Returns
| Type | Description |
|---|---|
datetime.datetime | The 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
| Name | Type | Description |
|---|---|---|
| value | any | The input value to validate and convert, which can be a string, date, or datetime object |
Returns
| Type | Description |
|---|---|
datetime.datetime | A 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
| Name | Type | Description |
|---|---|---|
| value | string | The string representation of the date and time to be parsed |
| format | string | The strftime-style format string used to interpret the input value |
Returns
| Type | Description |
|---|---|
datetime.datetime | The datetime object resulting from parsing the input string |