Creating a range of dates in Python

后端 未结 20 2356
栀梦
栀梦 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: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(),
        )
    ]
    

提交回复
热议问题