Formatting DateTimeField in Django
You can override DateTimeField
's value_to_string
method and add the changes there. For example:
class CustomDateTimeField(models.DateTimeField):
def value_to_string(self, obj):
val = self.value_from_object(obj)
if val:
val.replace(microsecond=0)
return val.isoformat()
return ''
And use it in model:
created = CustomDateTimeField(auto_now_add=True)
Change DateTimeField FORMAT in Django version 3.2.2
The DATETIME_FORMAT
setting [Django-doc] works with the formatting specifications like PHP does that.
So as format, you should use:
DATETIME_FORMAT = 'd-m-Y H:i:s'
Note that the formatting is slightly different [PHP datetime specs]. PHP uses i
for the minutes; and a lowercase s
for the seconds:
format character | Description | Example |
---|---|---|
… | … | … |
i | Minutes with leading zeros | 00 to 59 |
s | Seconds with leading zeros | 00 through 59 |
… | … | … |
How to change date_joined & datetimefield format in Django?
I solved with my custom DATETIME_FORMAT
settings.py
DATETIME_FORMAT = '%Y-%m-%d %H:%m'
serializers.py
class UserSerializer(serializers.ModelSerializer):
date_joined = serializers.DateTimeField(format=base.DATETIME_FORMAT, input_formats=None)
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'is_superuser', 'is_staff', 'is_active', 'date_joined',
'get_absolute_url', 'pk')
Django format DateTimeField output to {YYYY-MM-DD} {HH:MM AM/PM}
If you want to display it on a template, you should use the date filter :
{{ instance.created|date:"Y-m-d h:i A" }}
Or in Python, you can use the strftime function :
print(instance.created.strftime("%Y-%m-%d %I:%M %p"))
Django model DateTimeField set auto_now_add format or modify the serializer
Set DATETIME_FORMAT
in your settings.py
as specified here.
The default formatting to use for displaying datetime fields in any
part of the system. Note that ifUSE_L10N
is set to True, then the
locale-dictated format has higher precedence and will be applied
instead
The date part of your settings.py
should afterwards look like so:
DATETIME_FORMAT = '%d-%m-%Y %H:%M:%S'
USE_L10N = False
USE_TZ = False # if you plan to disable timezone support
Alternatively, you can manually change formats after retrieval by doing:
import datetime
datetime_str = '2016-05-18T15:37:36.993048Z'
old_format = '%Y-%m-%dT%H:%M:%S.%fZ'
new_format = '%d-%m-%Y %H:%M:%S'
new_datetime_str = datetime.datetime.strptime(datetime_str, old_format).strftime(new_format)
print(new_datetime_str)
#'18-05-2016 15:37:36'
This conversion can be added to your serializer or model as your proposed get_date()
method
Modify the DateField format shown on ModelAdmin list_display
In order to solve this problem I had to do 2 things.
- Write a funcion inside class StaffTimeSheetModelAdmin as suggested by @Clifton Avil D'Souza
- Convert time to my desired format
In order to do step 2, I created a helper funcion called day_hour_format_converter in whch I had to perform UTC to local time convertion because by default the time stored in the database was in UTC and I was displaying wrong hour values
models.py was not modified. This is my updated code:
On admin.py
from django.utils.timezone import now, localtime
def day_hour_format_converter(date_time_UTC):
local_time = localtime(date_time_UTC)
return str(local_time.year) +'-'+ str(local_time.month) +'-'+ str(local_time.day) + ' , ' + str(local_time.hour) +':'+ str(local_time.minute)
class StaffTimeSheetModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size':'50'})},
models.TextField: {'widget': Textarea(attrs={'rows':2, 'cols':50})},
}
def task_belongs_to_project_order (self,staff_time_sheet_obj):
return "\n".join([str(order.order_project.project_number) + "-" + str(order.order_number) for order in staff_time_sheet_obj.task_belongs_to_order.all()])
def start_time(self, staff_time_sheet_obj):
if staff_time_sheet_obj.task_start_time:
return day_hour_format_converter(staff_time_sheet_obj.task_start_time)
def end_time(self, staff_time_sheet_obj):
if staff_time_sheet_obj.task_end_time:
return day_hour_format_converter(staff_time_sheet_obj.task_end_time)
list_display = ('time_sheet_owner','task_belongs_to_project_order','start_time','end_time','task_description')
search_fields = ['task_start_time','task_description','task_belongs_to_order__order_number','task_belongs_to_order__order_project__project_number'] #TODO be able to look for "project-order" as a monolitic expression
list_filter = ('time_sheet_owner','task_start_time')
How can I set a DateField format in django from the model?
As @bruno as mentioned in his answer, input_formats
is a forms field, however it can be used to control the date format saved from the model.
In settings.py
set DATE_INPUT_FORMATS
as below:
DATE_INPUT_FORMATS = ['%d-%m-%Y']
And in your form you could do something like below:
class ClientDetailsForm(ModelForm):
date_of_birth = DateField(input_formats=settings.DATE_INPUT_FORMATS)
class Meta:
model = ModelA
Related Topics
Check If Values of Multiple Columns Are the Same (Python)
How to Merge Elements in List in Python With Condition
How to Install Pypdf2 Module Using Windows
How to Write Python Array (Data = []) to Excel
How to Cleanly Uninstall Ansible
Turn String into a List and Remove Carriage Returns (Python)
Python: How to Keep Repeating a Program Until a Specific Input Is Obtained
How to Locate the Index With in a Nested List Python
How to Create a for Loop That Goes Through All Diagonal Possibilities of a List
Python Overflowerror: Int Too Large to Convert to Float
How to Dynamically Build a Json Object
Access Is Denied When Trying to Pip Install a Package on Windows
Check If Key Exists in a Python Dict in Jinja2 Templates
Pandas: Group by Name and Take Row With Most Recent Date
How to Print the Even-Indexed and Odd-Indexed Characters of Strings