【问题标题】:Get all months and years in a range获取范围内的所有月份和年份
【发布时间】:2020-07-29 00:59:24
【问题描述】:

我正在编写一个 django 应用程序,其中我有基于日期时间字段存储的记录。

        first_record = MyModel.objects.filter().order_by('-added').first()
        first_record = (first_record.added.month, first_record.added.year)
        last_record = MyModel.objects.filter().order_by('-added').first()
        last_record = (last_record.added.month, last_record.added.year)

现在我想列出第一条记录和最后一条记录之间的所有月份/年份。一个粗略的想法是:

for i in range(first_record, last_record):
    # do something

range 函数应该给我一个列表进行迭代,看起来像这样:

[('01','2018'),('02','2018'),('03','2018'),....,('11','2020'),('12','2020')]

任何想法我该怎么做?

(last_record.added.month, last_record.added.year) 也是获取包含月份和年份的元组的正确方法。请注意,例如,我希望第一个月的月份格式为 01 而不是 1

【问题讨论】:

  • 01 不是有效整数,您的意思是要将月份和年份作为字符串吗?
  • 啊,是的,正确。

标签: python django django-models


【解决方案1】:

我相信 Django 有一个内置函数。你可以这样做:

>>> Entry.objects.dates('pub_date', 'month')
[datetime.date(2005, 2, 1), datetime.date(2005, 3, 1)]
>>> Entry.objects.dates('pub_date', 'week')
[datetime.date(2005, 2, 14), datetime.date(2005, 3, 14)]

翻译成你的代码,会是这样的

MyModel.objects.dates('added', 'month')

Documentation

【讨论】:

  • MyModel.objects.dates('added', 'month'),不是吗?
【解决方案2】:

您可以使用 dateutil.relativedelta 来做到这一点 这是代码

from dateutil.relativedelta import relativedelta
import datetime

result = []

today = datetime.date.today()
current = datetime.date(2010, 8, 1)    

while current <= today:
    result.append(current)
    current += relativedelta(months=1)

了解更多 https://dateutil.readthedocs.io/en/latest/relativedelta.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 2022-01-05
    相关资源
    最近更新 更多