varad
varad

Reputation: 8029

django date field get day of a week like sunday monday

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 ??

Upvotes: 6

Views: 14631

Answers (2)

Allen Shaw
Allen Shaw

Reputation: 1492

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)

Upvotes: 1

Chris
Chris

Reputation: 137179

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" }}

Upvotes: 9

Related Questions