【问题标题】:Can i extract only date from the datetime field data which is already in database?我可以只从数据库中已经存在的日期时间字段数据中提取日期吗?
【发布时间】:2018-10-30 10:53:24
【问题描述】:

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

【问题讨论】:

  • 删除Client.objects.all() 上完全无用的循环,只保留最后两个语句。还请记住,您有一个交互式 python shell (./manage.py shell),您可以使用它来测试您的查询。

标签: python postgresql django-models


【解决方案1】:

对于您的这个特定对象:

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

在提取“lastConnection”时,您可以使用 datetime 模块中的“.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')

# 您的 current_date 将采用 dd/mm/yyyy 格式

月 = current_date.month

#month 将指定从收到日期开始的月份。

【讨论】:

    【解决方案2】:
     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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多