我可以仅从数据库中已有的日期时间字段数据中提取日期吗?

时间:2018-10-30 10:53:25

标签: python postgresql django-models

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

这是我的记录,客户端模块就是这样

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

实际上,我想从数据库中获取上个月的记录,因此,如果有人可以帮助,那就太好了。

 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')

2 个答案:

答案 0 :(得分:1)

对于您的特定对象:

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

提取'lastConnection'时,可以从日期时间模块中使用“ .strftime('%d /%m /%Y')”。

例如:

导入日期时间

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')

#您的当前日期将采用dd / mm / yyyy格式

month = current_date.month

#个月将从接收日期起指定月份。

答案 1 :(得分:0)

 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)

这就是我用来解决问题的方法。