Creating a range of dates in Python

后端 未结 20 2089
栀梦
栀梦 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:50

    I know this has been answered, but I'll put down my answer for historical purposes, and since I think it is straight forward.

    import numpy as np
    import datetime as dt
    listOfDates=[date for date in np.arange(firstDate,lastDate,dt.timedelta(days=x))]
    

    Sure it won't win anything like code-golf, but I think it is elegant.

    0 讨论(0)
  • 2020-11-22 11:52

    You can also use the day ordinal to make it simpler:

    def date_range(start_date, end_date):
        for ordinal in range(start_date.toordinal(), end_date.toordinal()):
            yield datetime.date.fromordinal(ordinal)
    

    Or as suggested in the comments you can create a list like this:

    date_range = [
        datetime.date.fromordinal(ordinal) 
        for ordinal in range(
            start_date.toordinal(),
            end_date.toordinal(),
        )
    ]
    
    0 讨论(0)
提交回复
热议问题