5

Possible Duplicate:
Iterating through a range of dates in Python

I have two entries:

date1 = 2004.09.25
date2 = 2004.10.08

I want to wrote a script in Python that recognizes the date range and print them. something like this:

for i in range(date1:date2):
    print i

Do I need to define the dates in a particular format for dates? The expected output is like:

2004.09.25
2004.09.26
.
.
.
2004.10.08
Community
  • 1
  • 1
f.ashouri
  • 5,409
  • 13
  • 44
  • 52

3 Answers3

26

Your first step should have been to look at the python datetime library.

Overall, your first solution could look something like this:

date1 = datetime.date(2004, 9, 25)
date2 = datetime.date(2004, 10, 8)
day = datetime.timedelta(days=1)

while date1 <= date2:
    print date1.strftime('%Y.%m.%d')
    date1 = date1 + day

(one thing to note: this will obviously clobber your date1 variable)

I would later refactor this into a daterange function so that you can do something closer to what you did; it would look like

for d in daterange(date1, date2):
    print d.strftime('%Y.%m.%d')

Later on, when you develop your python skills, it could like like this:

for i in range((date2 - date1).days + 1):
    print (date1 + datetime.timedelta(days=i)).strftime('%Y.%m.%d')

Or this, which would be my final version:

def daterange(d1, d2):
    return (d1 + datetime.timedelta(days=i) for i in range((d2 - d1).days + 1))

for d in daterange(date1, date2):
    print d.strftime('%Y.%m.%d')
forivall
  • 9,504
  • 2
  • 33
  • 58
3

Use the builtin datetime module.

Firstly, split your dates (assuming it is a string) by each . and pass the lists to datetime.date

date1 = datetime.date(*date1.split('.'))
date2 = datetime.date(*date2.split('.'))

Then get the ordinal of each of the dates (number of days since Jan 1 0001)

date1 = date1.toordinal()
date2 = date2.toordinal()

Then, use a for loop, and the fromordinal function to convert an ordinal to a date

for i in range(date1, date2 + 1):
    print date.fromordinal(i).strftime('%Y.%m.%d')

Putting it all together:

date1 = datetime.date(*date1.split('.')).toordinal()
date2 = datetime.date(*date2.split('.')).toordinal()
for i in range(date1, date2 + 1):
    print date.fromordinal(i).strftime('%Y.%m.%d')
Volatility
  • 31,232
  • 10
  • 80
  • 89
2

using the ordinal functions it would go something like this:

import datetime

DATE1 = datetime.date(2004,9,25)
DATE2 = datetime.date(2004,10,8)
D1 = datetime.date.toordinal(DATE1)
D2 = (datetime.date.toordinal(DATE2))+1


for i in range(D1,D2):
    print datetime.date.fromordinal(i)
William
  • 121
  • 2