Juan Carlos Asuncion
Juan Carlos Asuncion

Reputation: 967

Get date from a Django DateTimeField

I would like to request some assistance regarding this matter

I am learning django and trying out some codes but I hit a brick wall at trying to get the date only from a model's DateTimeField

here's the code that I am working on:

class APPLICANT_DATA(models.Model):
    SCHEDULED_AT = models.DateTimeField(null=True, blank=True)


def somefunction():
    app_data = APPLICANT_DATA.objects.all()
    for item in app_data:
        the_date = str(item.SCHEDULED_AT.strftime("%B-%d-%Y")) + ", " + the _date

And I am getting ('NoneType' object has no attribute 'strftime') even though my model contains 3 records that all have date and time

What am I doing wrong? any advice for a newbie? many thanks.

Upvotes: 35

Views: 69739

Answers (4)

Walulya francis
Walulya francis

Reputation: 583

class YourModel(models.Model):
    you_field = models.CharField(max_length=255)
    created = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        date = self.created.date()
        return "%s" % str(date)

you can try it on the object

obj = YourModel.objects.filter(pk=1).get()
date = obj.created.date()

Upvotes: 0

phep
phep

Reputation: 581

While in the given example the problem is most probably due to the object truly being None, as said in other answers, please note that you might come across such a situation in test code if you forget to clean your data by calling, e.g. full_clean() on your DateTimeField as in :

test_obj = YourModel(
    date=datetime.datetime(2016,2,26,tzfinfo=GM1),
    ...
)
test_obj.full_clean() # <-- don't forget this or you'll get a NoneType object
test_obj.save()

Upvotes: 0

bakkal
bakkal

Reputation: 55448

DateTimeField becomes a datetime.datetime object in Python

If you need a date object to manipulate later on, you could pull the datetime.date object directly from your DateTimeField(), using datetime.datetime.date() like below:

class ApplicantData(models.Model):
    scheduled_at = models.DateTimeField(null=True, blank=True)

date = application_data.scheduled_at.date()

This works because Django will translate the DateTimeField into the Python type datetime.datetime, upon which we have called date().

Format the datetime.date like you wish

Then from that, you get a datetime.date object, that you can format like you wish, using datetime.date.strftime().

If you don't need a date object, you can also use strftime on your datetime.datetime object too, no problems with that. Except that your had a None field in your object.

Dealing with NULL/None fields

If you want to allow for NULL values in scheduled_at you can do:

if application_data.scheduled_at is not None:
      date = application_data.scheduled_at.date()

Upvotes: 52

Shang Wang
Shang Wang

Reputation: 25559

SCHEDULED_AT is set to null=True, so sometimes item.SCHEDULED_AT doesn't have value so it's None. If you do a .strftime on None it will have the error you got. null=True means django model allows the field to have NULL value.

By the way, it's really bad practice to use all upper case for model and field names, model name should be camel case and fields should be lower case with underscore. You model name should be ApplicantData, field name should be scheduled_at.

Upvotes: 1

Related Questions