简体   繁体   English

获取范围内的所有月份和年份

[英]Get all months and years in a range

I am writing a django application where I have records stored on the basis of datetimefield.我正在编写一个 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)

Now I want to make a list of all months/year between the first record and last record.现在我想列出第一条记录和最后一条记录之间的所有月份/年份。 A rough idea is:一个粗略的想法是:

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

Where the range function is supposed to give me a list to iterate over which looks like this:范围 function 应该给我一个列表来迭代它看起来像这样:

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

Any ideas how do I do that?任何想法我该怎么做?

Also is (last_record.added.month, last_record.added.year) the right way to get a tuple containing month and year.也是(last_record.added.month, last_record.added.year)获取包含月份和年份的元组的正确方法。 Note that I want months in the format 01 instead of 1 for first month for example.请注意,例如,我希望月份格式为01而不是第一个月的1

I believe Django has a built-in function.我相信 Django 有一个内置的 function。 You can do:你可以做:

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

Which, translated into your code, will be something like翻译成您的代码,将类似于

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

Documentation 文档

You can do this by using dateutil.relativedelta Here is the code您可以使用 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)

Know more abou in https://dateutil.readthedocs.io/en/latest/relativedelta.html了解更多关于https://dateutil.readthedocs.io/en/latest/relativedelta.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM