How to Display Only the Date from a DateTimeField Object in Django



Python


In this article, we show how to display only the date from a DateTimeField object in Django.

So let's say that you create a DateTimeField for a model in order to get a timestamp for when an instance was created or you create a DateTimeField to see when an instance was last edited. However, when you are showing when it was published or when it was last edited, you may just want to show the date, and not the full datetime.

Showing the full datetime may be too specific. You wouldn't need to show that the post was published on December 6,2017 at 7:15am. This, for the most part, is too specific. Instead you would just want to display December 6, 2017.

So how can this be done in Django?

Well, Django has a template filter tag that allows datetime objects to be formatted into whatever we want.

Let's say that we have a datetime object, we can show only the day, month, and year with the following line in our template file.



F stands for the full month name.

d stands for the numerical day of the month.

Y stands for the 4-digit year.

If you want the day of the week added, the symbol would be, D, for the textual 3 letters, such as 'Fri'. If you want the full day of the week, the symbol would be, l, such as 'Friday'.

If you want the capitalized 3-letter shorthand for the month, the symbol is, M. If you want the lowercase 3-letter shorthand for the month, the symbol is, b.

To see a full list of Django date template filters, see the following link: Djano date template filters

Using the date template filter tag in Django is probably the easiest way to display a datetime object in any date format that you want. However, it is not the only way. You can also create our own custom function in the models.py file that does the same thing.


Custom Function in the models.py File

We can also create our own custom function in the models.py file that can format a datetime object.

This method relies more on Python code rather than built-in Django code.

In the models.py file below, we create a custom function called datepublished, which returns the DateTimeField of pub_date.



So now we've created a custom function, datepublished, which formats the DateTimeField of pub_date.

%B stands for the full month name.

%d stands for the numerical day of the month.

%Y stands for the 4-digit year.

Now to show the date published on a template file, you would use the following code below.



Again, you can customize this to whatever you want. The full list of codes for formatting DateTimeField objects in Python can be found here: Python Date Format Codes

This is probably not necessary because Django has written code already so that we don't have to create our own custom function. However, if you want more native control, you may want to write your own custom Python code.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...