Krolique
Krolique

Reputation: 682

python, datetime.date: difference between two days

I'm playing around with 2 objects {@link http://docs.python.org/library/datetime.html#datetime.date}

I would like to calculate all the days between them, assuming that date 1 >= date 2, and print them out. Here is an example what I would like to achieve. But I don't think this is efficient at all. Is there a better way to do this?

# i think +2 because this calc gives only days between the two days, 
# i would like to include them
daysDiff = (dateTo - dateFrom).days + 2

while (daysDiff > 0):
     rptDate = dateFrom.today() - timedelta(days=daysDiff)
     print rptDate.strftime('%Y-%m-%d')
     daysDiff -= 1

Upvotes: 4

Views: 9742

Answers (1)

Ben James
Ben James

Reputation: 125157

I don't see this as particularly inefficient, but you could make it slightly cleaner without the while loop:

delta = dateTo - dateFrom

for delta_day in range(0, delta.days+1): # Or use xrange in Python 2.x
    print dateFrom + datetime.timedelta(delta_day)

(Also, notice how printing or using str on a date produces that '%Y-%m-%d' format for you for free)

It might be inefficient, however, to do it this way if you were creating a long list of days in one go instead of just printing, for example:

[dateFrom + datetime.timedelta(delta_day) for delta_day in range(0, delta.days+1)]

This could easily be rectified by creating a generator instead of a list. Either replace [...] with (...) in the above example, or:

def gen_days_inclusive(start_date, end_date):
    delta_days = (end_date - start_date).days
    for day in xrange(delta_days + 1):
        yield start_date + datetime.timedelta(day)

Whichever suits your syntax palate better.

Upvotes: 6

Related Questions