Erick
Erick

Reputation: 250

remove time from django DateTime in Django

So i need to remove from date Time, so i only get date, year and month.

"2014-04-17T00:00:00"

I looked at different opportunities but it didn't work

class Inventory(models.Model):
manufacturer = models.CharField(max_length=255)
model        = models.CharField(max_length=255)
description  = models.TextField(max_length=255)
count        = models.IntegerField(max_length= 255, default=1)
location     = models.ForeignKey('Location',  null=True, blank=True)
cover        = models.FileField(upload_to = 'static/images/', default = 'static/images/no-image.png')
created      = models.DateTimeField(auto_now_add=True)
barcode      = models.CharField(max_length=255)
assigned     = models.ForeignKey(User, blank=True, null=True)
checked      = models.BooleanField(default=False)
modified     = models.DateTimeField(default=datetime.datetime.now)
tags         = TaggableManager(through=None, blank=True)

def __unicode__(self):
    return '%s' % date(self.modified, "n/j/Y")

def format_date(obj):
    return obj.modified.strftime('%d %b %Y %H:%M')
    format_date.short_description = 'Modified'

Upvotes: 5

Views: 9381

Answers (5)

koro
koro

Reputation: 356

You can store the time if required, else you can use the Date Field as mentioned here.

However after using DateTimeField in your models, to fetch only date via Django's ORM you can simply do the following:

To Get the Date Only:

User.objects.filter('created_at__date')

To Get the Month Only:

User.objects.filter('created_at__month')

To Get the Year Only:

User.objects.filter('created_at__year')

Upvotes: 0

Nifemi Sola-Ojo
Nifemi Sola-Ojo

Reputation: 867

Just replace modified = models.DateTimeField(default=datetime.datetime.now) with modified = models.DateField(default=datetime.date.now)

Upvotes: 0

Rizwan Mumtaz
Rizwan Mumtaz

Reputation: 3955

this works for me.

def get_date(self):
    return self.modified.date()

Upvotes: 3

Ralph
Ralph

Reputation: 430

This is code will solve your problem:

def get_date(dt):
    """
    Remove the time from datetime field.
    """
    return dt.strftime("%Y-%M-%d")

@property
def modified_date(self):
    return self.get_date(self.modified)

You can also use DateField instead of DateTimeField

If you want in django templatetag date formatting click here.

Upvotes: 0

Laurent
Laurent

Reputation: 1806

You can parse the strftime with dateutil.parser :

import dateutil.parser
datetime_date = dateutil.parser.parse(strf_date)

And then get a strftime date with the part of the datetime you need. In your case, Year, Month, Day :

date_only = datetime_date.strftime("%Y-%M-%d")

Upvotes: 1

Related Questions