Creating a loop for two dates

Possible duplicate:
Python date range iteration

I have two entries:

date1 = 2004.09.25 date2 = 2004.10.08 

I want to write a script in Python that recognizes a range of dates and prints them. something like that:

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

Do I need to define dates in a specific format for dates? The expected result is as follows:

 2004.09.25 2004.09.26 . . . 2004.10.08 
+4
source share
3 answers

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

In general, your first solution might 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 note: this will obviously hide your date1 variable)

I will later reorganize 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, when you develop your python skills, he may like it like this:

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

Or is this what would be my latest 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') 
+15
source

Use the built-in datetime module.

First, separate your dates (assuming it's 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 each of the dates (number of days from January 1, 0001)

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

Then use the for loop and fromordinal function to convert the serial number to 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') 
+2
source

using ordinal functions, it will look 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) 
+2
source

All Articles