Python: get all months in range?

后端 未结 9 1182
天涯浪人
天涯浪人 2020-12-15 18:00

I want to get all months between now and August 2010, as a list formatted like this:

[\'2010-08-01\', \'2010-09-01\', .... , \'2016-02-01\']
<
9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 18:26

    I had a look at the dateutil documentation. Turns out it provides an even more convenient way than using dateutil.relativedelta: recurrence rules (examples)

    For the task at hand, it's as easy as

    from dateutil.rrule import *
    from datetime import date
    
    months = map(
        date.isoformat,
        rrule(MONTHLY, dtstart=date(2010, 8, 1), until=date.today())
    )
    

    The fine print

    Note that we're cheating a little bit, here. The elements dateutil.rrule.rrule produces are of type datetime.datetime, even if we pass dtstart and until of type datetime.date, as we do above. I let map feed them to date's isoformat function, which just turns out to convert them to strings as if it were just dates without any time-of-day information.

    Therefore, the seemingly equivalent list comprehension

    [day.isoformat()
        for day in rrule(MONTHLY, dtstart=date(2010, 8, 1), until=date.today())]
    

    would return a list like

    ['2010-08-01T00:00:00',
     '2010-09-01T00:00:00',
     '2010-10-01T00:00:00',
     '2010-11-01T00:00:00',
     ⋮
     '2015-12-01T00:00:00',
     '2016-01-01T00:00:00',
     '2016-02-01T00:00:00']
    

    Thus, if we want to use a list comprehension instead of map, we have to do something like

    [dt.date().isoformat()
        for dt in rrule(MONTHLY, dtstart=date(2010, 8, 1), until=date.today())]
    

提交回复
热议问题