Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django date field get day of a week like sunday monday

Tags:

python

django

I have a DateField in django whose default value is set to timezone.now

How can I get the week of the day. I mean the day is either sunday or monday or other ??

like image 780
varad Avatar asked Mar 09 '23 20:03

varad


2 Answers

A Django DateField is

represented in Python by a datetime.date instance

So in Python code you can use date.weekday() or date.isoweekday() on it.

In a template you should use the date filter, e.g.

Today is {{ date_variable|date:"l" }}
like image 185
Chris Avatar answered Mar 12 '23 10:03

Chris


You can use a small piece of code to do that:

import datetime
from django.db import models

def get_monday():
    today = datetime.datetime.now()
    return today - datetime.timedelta(today.weekday())

class MyModel(models.Model):
    date = models.DateField(default=get_monday)

also sunday:

def get_sunday():
    today = datetime.datetime.now()
    return today + datetime.timedelta(7 - today.weekday() - 1)
like image 41
Allen Shaw Avatar answered Mar 12 '23 09:03

Allen Shaw