Creating a range of dates in Python

后端 未结 20 2357
栀梦
栀梦 2020-11-22 11:02

I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?

20条回答
  •  情深已故
    2020-11-22 11:25

    From the title of this question I was expecting to find something like range(), that would let me specify two dates and create a list with all the dates in between. That way one does not need to calculate the number of days between those two dates, if one does not know it beforehand.

    So with the risk of being slightly off-topic, this one-liner does the job:

    import datetime
    start_date = datetime.date(2011, 01, 01)
    end_date   = datetime.date(2014, 01, 01)
    
    dates_2011_2013 = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]
    

    All credits to this answer!

提交回复
热议问题