Riya Gupta
Riya Gupta

Reputation: 63

Can i extract only date from the datetime field data which is already in database?

{'uid': u'5db9d835-da23-4abc-a7cd-6beba0dd871f', 'lastConnection': datetime.datetime(1970, 1, 1, 6, 0, tzinfo=)},

This is the record i have and the client module is like this

class Client(models.Model):
    uid = models.CharField(max_length=128)
    key = models.CharField(max_length=128)
    img = models.TextField()
    version = models.CharField(max_length=20)
    lastConnection = models.DateTimeField()
    role = models.CharField(max_length=128,default="")

    def __str__(self):
        return "%s"%self.uid

Actually i want to fetch last month records from the database So if someone could help it would be great.

 def handle(self, **options):
        clients=Client.objects.all()
        c=0
        for c in clients:

            d1 = Client.objects.filter(lastConnection=c.lastConnection).order_by('uid').values('lastConnection','uid')
            last_month = datetime.today() - timedelta(days=30)
            items = Client.objects.filter(lastConnection__gte=last_month).order_by('uid')

Upvotes: 0

Views: 66

Answers (2)

Riya Gupta
Riya Gupta

Reputation: 63

 def handle(self, **options):
        clients=Client.objects.all()
#       print clients
        c=0
        for c in clients:
            d1 = Client.objects.filter(lastConnection=c.lastConnection).order_by('uid').values('lastConnection','uid')
        last_month = datetime.today() - timedelta(days=30)
        cls=items = Client.objects.filter(lastConnection__gte=last_month).order_by('uid').values('lastConnection','uid')
        print list(cls)

This is what i have used to solve my problem.

Upvotes: 0

Omkar
Omkar

Reputation: 178

For your this particular object :

{'uid': u'5db9d835-da23-4abc-a7cd-6beba0dd871f', 'lastConnection': datetime.datetime(1970, 1, 1, 6, 0, tzinfo=)}

while extracting 'lastConnection' you can use ".strftime('%d/%m/%Y')" from datetime module.

E.g. :

import datetime

data = {'uid': u'5db9d835-da23-4abc-a7cd-6beba0dd871f', 'lastConnection': datetime.datetime(1970, 1, 1, 6, 0, tzinfo=)}

current_date = (data['lastConnection']).strftime('%d/%m/%Y')

# Your current_date will be in dd/mm/yyyy format

month = current_date.month

# month would have specified month from date received.

Upvotes: 1

Related Questions