How to Get Day from Datetime field in Django?

Published On: 09/09/2022 | Category: Django

Hi Dev,

In this quick example, let's see how to get day from datetime field in django. This post will give you simple example of how to get day name from datetime field in django. Here you will learn How to extract day from datetime field in django. you can understand a concept of how to get day from datetime in django. you will do the following things for how to get only day from datetime field in django.

For in this example, let's talk about we're running a site where a user can post content on the site. We may not want to put the entire datetimefield object, where it has the day, We may just want to put the day.

So, let's say, for example, we just want to extract the day name from the DateTimeField.

let's see bellow example here you will learn how to get day from datetime field in django.

Django Admin Interface:
from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify

class Article(models.Model):
    title= models.CharField(max_length=300)
    url= models.SlugField(max_length=300)
    content= models.TextField()
    pub_date = models.DateTimeField(auto_now_add= True)
    author= models.ForeignKey(User,on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        self.url= slugify(self.title)
        super(Article, self).save(*args, **kwargs)

    def __str__(self):
        return self.title

    #Get Day Name
    def getdayname(self):
        return self.pub_date.strftime('%a')
from django.shortcuts import render, get_object_or_404,redirect
from .forms import *
from .models import *

def detail_post_view(request, id=None):
    postobj= Article.objects.all()
    context={'postobj': postobj}
    return render (request, 'detail.html', context)
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-9">
                <div class="card">
                    <div class="card-header">
                        <h4>How to Get Day from Datetime field in Django? - <span class="text-primary"></span></h4>
                    <div class="card-body">
                        <table class="table table-bordered">
                                    <th>Publish Day</th>
                                {% for post in postobj %}
                                    <td>{{ post.title }}</td>
                                    <td class="text-primary">{{ post.getdayname }}</td>
                                {% endfor %}

I Hope It will help you....

Happy Coding!