Generating all dates within a given range in python

前端 未结 9 550
青春惊慌失措
青春惊慌失措 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 08:59

    Assuming your dates are already as a datetime.date class you can use .fromordinal and .toordinal to create this oneliner.

    from datetime import date
    
    start_date = date(2011, 5, 3)
    end_date = date(2011, 5, 10)
    
    [date.fromordinal(i) for i in range(start_date.toordinal(), end_date.toordinal())]
    

    The result is exclusive end_date. Use end_date.toordinal() + 1 for a range inclusive end_date.

提交回复
热议问题