抱歉我的英文。
我有两个约会(DateTime):
latest_client = Client.objects.all().latest('id').ordered_at
first_client = Client.objects.order_by()[0].ordered_at
2011-04-22 15: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)
建议请算法,怎么样?
答案 0 :(得分:4)
这是一个生成器,可以让您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