Generate list of months between interval in python

后端 未结 10 1169
庸人自扰
庸人自扰 2020-12-08 02:14

I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows:

date1 = \"2014-10-10\"  #         


        
10条回答
  •  不思量自难忘°
    2020-12-08 02:43

    Having done similar stuff previously, I took a stab at solving this. Using distinct components for doing this is more flexible and enables you to mix and match them for different use-cases. They also can be tested more easily this way, as you can see by the doctests in iterate_months.

    Also I suggest to use datetime.date objects for your input as you can just do more with those. To do that you'll have to first parse your input string, but this is very easily done.

    Parsing the date-strings

    def datify(date):
        if isinstance(date, datetime.date):
            return date
        elif isinstance(date, datetime.datetime):
            return date.date()
        else:
            # taken from simleo's answer
            return datetime.strptime(date, "%Y-%m-%d")
    

    First, we iterate through the months

    import datetime
    
    
    def iterate_months(start_date, end_date):
        """Iterate monthly between two given dates.
    
        Emitted will be the first day of each month.
    
        >>> list(iterate_months(datetime.date(1999, 11, 1),
        ...                     datetime.date(2000, 2, 1)))
        [datetime.date(1999, 11, 1), datetime.date(1999, 12, 1),\
     datetime.date(2000, 1, 1), datetime.date(2000, 2, 1)]
    
        """
        assert isinstance(start_date, datetime.date)
        assert isinstance(end_date, datetime.date)
        assert start_date < end_date
    
        year = start_date.year
        month = start_date.month
        while True:
            current = datetime.date(year, month, 1)
            yield current
            if current.month == end_date.month and current.year == end_date.year:
                break
            else:
                month = ((month + 1) % 12) or 12
                if month == 1:
                    year += 1
    
    
    if __name__ == '__main__':
        import doctest
        doctest.testmod()
    

    To format your dates, use something like this

    def format_month(date):
        return date.strftime(r"%b-%y")
    

    Putting it all together

    start = datify("2014-10-10")
    end = datify("2016-01-07")
    
    for entry in iterate_months(start, end):
        print format_month(entry)
    

    Or save it as a list:

    result = list(iterate_months(start, end))
    

提交回复
热议问题