Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get date from a Django DateTimeField

Tags:

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.

like image 664
Juan Carlos Asuncion Avatar asked Feb 09 '16 19:02

Juan Carlos Asuncion


People also ask

How can I filter a date of a DateTimeField in django?

To filter a date of a DateTimeField in Python Django, we can use filter with a datetime. to call filter to return the results with the datetime_published field set to 2018-03-27.

What is DateTimeField in django?

DateTimeField is a date and time field which stores date, represented in Python by a datetime. datetime instance. As the name suggests, this field is used to store an object of datetime created in python.

How do I get the current date and time in django?

First, open the views.py file of your Django application and import the datetime module. Next, use the datetime. now() method to get the current date and time value.


1 Answers

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() 
like image 103
bakkal Avatar answered Sep 20 '22 05:09

bakkal