开发者

Get the difference between dates in the form of list years and months

开发者 https://www.devze.com 2023-02-27 20:59 出处:网络
Sorry for my english. I have a two dates(DateTime): latest_client = Client.objects.all().latest(\'id\').ordere开发者_JAVA技巧d_at

Sorry for my english.

I have a two dates(DateTime):

latest_client = Client.objects.all().latest('id').ordere开发者_JAVA技巧d_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

I need to get the difference between dates in the form of list years and months:

2011(04,03,02,01)

2010(12,11,10,09,08,07,06,05,04,03)

Advice please algorithm, how?


Here is a generator that gives you datetime.date() spanning the months between start and end (inclusive)

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

Demonstration:

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

精彩评论

暂无评论...
验证码 换一张
取 消