When using a TimeField
in a Django model, the microseconds part of the time value is always set to 0
after click save. Although the database stores the microseconds correctly (e.g., 15:42:21.222000
), the admin panel rounds or truncates them, often displaying 15:42:21
instead. This can cause confusion for users who rely on precise time values. As updating any other field in the instance from the admin form, it overrides the microseconds part of the time to be .00000
.
I Found this part in the Django docs in the part related to the Widgets:
By default, the microseconds part of the time value is always set to
0
. If microseconds are required, use a subclass with thesupports_microseconds
attribute set toTrue
.
SO I have created a custom widget:
from django.forms.widgets import TimeInput
from django.contrib import admin
class MicrosecondTimeInput(TimeInput):
input_type = "text"
def __init__(self, attrs=None, format=None):
# Set supports_microseconds to True
self.supports_microseconds = True
super().__init__(attrs, format)
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
TimeField: {"widget": MicrosecondTimeInput(format="%H:%M:%S.%f")},
}
And After Doing that the admin forms shows the microseconds part correctly, but the field type converted to a string
not time
, So it became a little confusing.