1

我有以下模型:

Deal(models.Model):
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()    

我想遍历给定的年份

year = '2010'

对于一年中的每个月,我想执行一个查询以查看该月是否在 start_date 和 end_date 之间。

如何迭代给定的年份?使用月份进行查询?

SELECT * FROM deals WHERE month BETWEEN start_date AND end_date 

结果将告诉我是否在 2010 年 1 月和/或 2010 年 2 月等进行了交易。

4

1 回答 1

4

如何迭代给定的年份?

您可以使用python-dateutil 的 rrule。使用命令安装pip install python-dateutil

示例用法:

In [1]: from datetime import datetime

In [2]: from dateutil import rrule

In [3]: list(rrule.rrule(rrule.MONTHLY, dtstart=datetime(2010,01,01,00,01), count=12))  
Out[3]: 
[datetime.datetime(2010, 1, 1, 0, 1),
 datetime.datetime(2010, 2, 1, 0, 1),
 datetime.datetime(2010, 3, 1, 0, 1),
 datetime.datetime(2010, 4, 1, 0, 1),
 datetime.datetime(2010, 5, 1, 0, 1),
 datetime.datetime(2010, 6, 1, 0, 1),
 datetime.datetime(2010, 7, 1, 0, 1),
 datetime.datetime(2010, 8, 1, 0, 1),
 datetime.datetime(2010, 9, 1, 0, 1),
 datetime.datetime(2010, 10, 1, 0, 1),
 datetime.datetime(2010, 11, 1, 0, 1),
 datetime.datetime(2010, 12, 1, 0, 1)]

使用月份进行查询?

你可以像这样迭代几个月:

In [1]: from dateutil import rrule

In [2]: from datetime import datetime

In [3]: months = list(rrule.rrule(rrule.MONTHLY, dtstart=datetime(2010,01,01,00,01), count=13))

In [4]: i = 0

In [5]: while i < len(months) - 1:
   ...:         print "start_date", months[i], "end_date", months[i+1]
   ...:         i += 1
   ...:     
start_date 2010-01-01 00:01:00 end_date 2010-02-01 00:01:00
start_date 2010-02-01 00:01:00 end_date 2010-03-01 00:01:00
start_date 2010-03-01 00:01:00 end_date 2010-04-01 00:01:00
start_date 2010-04-01 00:01:00 end_date 2010-05-01 00:01:00
start_date 2010-05-01 00:01:00 end_date 2010-06-01 00:01:00
start_date 2010-06-01 00:01:00 end_date 2010-07-01 00:01:00
start_date 2010-07-01 00:01:00 end_date 2010-08-01 00:01:00
start_date 2010-08-01 00:01:00 end_date 2010-09-01 00:01:00
start_date 2010-09-01 00:01:00 end_date 2010-10-01 00:01:00
start_date 2010-10-01 00:01:00 end_date 2010-11-01 00:01:00
start_date 2010-11-01 00:01:00 end_date 2010-12-01 00:01:00
start_date 2010-12-01 00:01:00 end_date 2011-01-01 00:01:00

用查询替换“打印”语句。随意调整它以适应您的需求。

可能有更好的方法,但可以完成这项工作。

于 2012-05-21T09:11:19.560 回答