Formatting Datetimefield in Django

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 characterDescriptionExample
iMinutes with leading zeros00 to 59
sSeconds with leading zeros00 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 if USE_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.

  1. Write a funcion inside class StaffTimeSheetModelAdmin as suggested by @Clifton Avil D'Souza
  2. 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



Leave a reply



Submit