Python: get all months in range?

后端 未结 9 1186
天涯浪人
天涯浪人 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:44

    use datetime and timedelta standard Python's modules - without installing any new libraries

    from datetime import datetime, timedelta
    
    now = datetime(datetime.now().year, datetime.now().month, 1)
    ctr = datetime(2010, 8, 1)
    list = [ctr.strftime('%Y-%m-%d')]
    
    while ctr <= now:
        ctr += timedelta(days=32)
        list.append( datetime(ctr.year, ctr.month, 1).strftime('%Y-%m-%d') )
    

    I'm adding 32 days to enter new month every time (longest months has 31 days)

提交回复
热议问题