获取列表年份和月份形式的日期之间的差异
问题描述:
对不起,我的英语不好。获取列表年份和月份形式的日期之间的差异
我有两个日期(日期时间): latest_client = Client.objects.all().latest('id').ordered_at
first_client = Client.objects.order_by()[0].ordered_at
2011-04-22十五点27分28秒 - latest_client
2010-03-17 21:00:0 - first_client
我需要以列表年和月的形式获取日期之间的差异:
2011(04,03,02,01)
2010(12,11,10,09,08,07,06,05 ,04,03)
请教算法,怎么样?
答
这里是一个发电机,让你跨越datetime.date()
起点和终点之间的个月(含)
from datetime import date, datetime
def spanning_months(start, end):
assert start <= end
current = start.year * 12 + start.month - 1
end = end.year * 12 + end.month - 1
while current <= end:
yield date(current // 12, current % 12 + 1, 1)
current += 1
示范:
>>> latest = datetime(2011, 4, 22, 15, 27, 28)
>>> first = datetime(2010, 3, 17, 21, 0, 0)
>>> for d in spanning_months(first, latest):
... print d
2010-03-01
2010-04-01
2010-05-01
2010-06-01
2010-07-01
2010-08-01
2010-09-01
2010-10-01
2010-11-01
2010-12-01
2011-01-01
2011-02-01
2011-03-01
2011-04-01
+0
非常感谢Martijn Pieters – Vladimir 2011-04-22 18:21:02
1.从年/月转换为12 *年+月份指数值。 2.使用'范围'。请对此进行编码,**更新**问题,我们会评论您的工作情况。 – 2011-04-22 17:43:45
已检查datetime.timedelta ??? – 2011-04-22 17:44:31
你需要完整的日期(例如'datetime.date(year,month,1)'')还是一个专门的结构(例如迭代'year,(month,month,month)''结构)? – 2011-04-22 17:57:38