Generating all dates within a given range in python

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

    Dates can be compared to each other just like numbers, and you can do date-related math with the datetime.timedelta object. There's no reason to use dateutil here, and there's no reason to hard-code the number of iterations a la 'range(9)'. This really becomes similar to how you'd deal with plain old numbers.

    >>> import datetime
    >>> date1 = '2011-05-03'
    >>> date2 = '2011-05-10'
    >>> start = datetime.datetime.strptime(date1, '%Y-%m-%d')
    >>> end = datetime.datetime.strptime(date2, '%Y-%m-%d')
    >>> step = datetime.timedelta(days=1)
    >>> while start <= end:
    ...     print start.date()
    ...     start += step
    ... 
    2011-05-03
    2011-05-04
    2011-05-05
    2011-05-06
    2011-05-07
    2011-05-08
    2011-05-09
    2011-05-10
    >>> 
    

提交回复
热议问题