Generating all dates within a given range in python

前端 未结 9 536
青春惊慌失措
青春惊慌失措 2021-02-02 08:31

I have two string variables which contain dates in yyyy-mm-dd format as follows :

date1 = \'2011-05-03\'
date2 = \'2011-05-10\'

I want to write

9条回答
  •  隐瞒了意图╮
    2021-02-02 09:02

    I like this one because it is intuitive and it gives an array of date strings.

    import re
    import datetime
    
    def datetime_to_str_date(dt):
        return re.sub(r'\T.+$','', dt.isoformat())
    
    start_date = datetime.datetime.strptime('2016-01-01', '%Y-%m-%d')
    end_date = datetime.datetime.today()
    num_of_days = (end_date - start_date).days
    
    date_list = map(
            datetime_to_str_date, 
            [start_date + datetime.timedelta(days=x) for x in range(0, num_of_days)]
    )
    

提交回复
热议问题