James
James

Reputation: 91

Django / Python - Extract Date from DateTimeField

Take the example model as follows:

import datetime

class Calendar(models.Model)

    def now():
        return datetime.date.today()

    def 24hrslater():
        return datetime.date.today() + datetime.timedelta(days=1)

    now = models.DateTimeField(default=now)
    24hrslater = models.DateTimeField(default=24hrslater)

Is there a way to extract just the date from these date time fields? I have tried the following (as suggested on another thread):

todaysdate = now.date()

But had no success with it. The error that comes up on the command line when running "python manage.py check" is:

AttributeError: 'DateTimeField' object has no attribute 'date'

Is there a way to do this?

Upvotes: 1

Views: 10832

Answers (2)

Håken Lid
Håken Lid

Reputation: 23084

I'm not sure that I understand your question correctly, but you can get the date from DateTimeFields like this.

from django.db import models
from django.utils import timezone

class Calendar(models.Model):

    now = models.DateTimeField(default=timezone.now)
    twenty_four_hours_later = models.DateTimeField(
        default=lambda: timezone.now() + timezone.timedelta(hours=24))

c = Calendar()
print(c.now.date())
print(c.twenty_four_hours_later.date())

Upvotes: 2

Exprator
Exprator

Reputation: 27533

def now():
    return datetime.today().date()

this will return the current date

Calendar.objects.filter(datetimefield__date='your_date')

Upvotes: 4

Related Questions