【问题标题】:Get data of previous months data in python django在python django中获取前几个月的数据
【发布时间】:2019-09-24 08:12:13
【问题描述】:

嗨,我正在使用 django,我的模型看起来像这样

class SignupMonthlyPoint(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='SignupMonthlyPoints')
    timestamp = models.DateTimeField(auto_now_add=True)
    value = models.FloatField()

我得到了最近 30 天这样的数据

def get_signupfromlinkmonthlypoints():
    total_for_last_month =request.user.profile.SignupMonthlyPoint.filter(
    timestamp__gt=datetime.datetime.now() - relativedelta(months=1)
    ).aggregate(
    total=Sum('value')
    )['total']
    print(total_for_last_month)

但是当我分析它最近 30 天的数据而不是上个月的数据时。我想让它像整个 8 月的数据,因为它是 9 月的最后一个月,然后是整个 7 月的数据,依此类推。

【问题讨论】:

    标签: python django python-3.x django-models python-dateutil


    【解决方案1】:

    我会从计算月份开始和结束日期开始:

    now = timezone.now()
    one_month_ago = datetime.datetime(now.year, now.month - 1, 1)
    month_end = datetime.datetime(now.year, now.month, 1) - datetime.timedelta(seconds=1)
    

    然后得到对应的SignupMonthlyPoints:

    SignupMonthlyPoint.objects.filter(user=request.user,
                                      timestamp__gt=one_month_ago,
                                      timestamp__lt=month_end)
    

    您可能必须在日期上使用 timezone.make_aware() 来添加时区并让 Django 识别它们

    【讨论】:

    • 我可以得到以前的 1,2,3 等月份的开始和结束日期吗?
    • 你也可以用__range代替__gt__lt
    • 当然,只需循环数个月并从中创建新的时间戳:for i in range(1,4): datetime(now.year, now.month - i, 1)
    • datetime.datetime:构造函数是datetime(year, month, day, ...)。您目前正在做的是获得当月的 2 日,例如2019-09-02.
    • 但请注意,此算法不适用于 1 月份,因为 0 月份不存在,并且会引发 ValueError
    猜你喜欢
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多