tags:

views:

218

answers:

3

I want to use a for loop to print every date between 2 dates. Actually going to merge this with a MySQL query to pass the date into the query itself and into the filename of the output.

So, how can I change this:

sum = 0
for i in range(1,11):
 print sum
 sum += i

To this?

InputDate = '2009-01-01'
for i in range('2009-01-01','2009-07-01'):
 print InputDate 
 InputDate += i

I realize there is something in rrule that does this exact function:

a = date(2009, 1, 1)
b = date(2009, 7, 1)
for dt in rrule(DAILY, dtstart=a, until=b):
 print dt.strftime("%Y-%m-%d")

But, I am restricted to older version of python.

This is the shell script version of what I am trying to do, if this helps clarify:

while [InputDate <= EndDate]
do
    sql="SELECT Date,SUM(CostUsd) FROM DailyStats WHERE Date = '$InputDate' GROUP BY Date"
    name=$(mysql -h -sN -u -p -e "$sql" > DateLoop-$InputDate.txt db)
    echo "$name"
    InputDate=$(( InputDate + 1 ))
done

So how can I do this in Python?

Adding follow up question here for readability. Unfortunately I can not use standard MySQL library as we have a proprietary setup with numerous instances running in parallel. The only way to run this type of query is to connect to one instance at a time, on the command line.

while day <= b: print "Running extract for :" day

sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = " + day + " GROUP BY Date"

os.system('mysql -h -sN -u -p -e " + sql + " > DateLoop-" + day + ".txt db')

day += one_day

+7  A: 

This will work:

import datetime

a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 7, 1)
one_day = datetime.timedelta(1)

day = a

while day <= b:
    # do important stuff
    day += one_day
balpha
Thank you balpha that did work perfectly. 1 follow up question. Is this the right way to pass the date as a variable into strings below:a = datetime.date(2009, 1, 1)b = datetime.date(2009, 7, 1)one_day = datetime.timedelta(1)day = awhile day <= b: print "Running extract for :" day sql="SELECT Date,SUM(CostUsd) FROM Stats d WHERE d.Date = $day GROUP BY Date" os.system('mysql -h -sN -u -p -e "$sql" > DateLoop-day.txt db') day += one_dayI realize there are modules/libraries for running this from python to MySQL, but I would rather run on command line in this case.Thanks again!
David Perron
That's pretty hard to read in a comment. Besides that, as you say yourself, you should really rethink the command line way. Using library bindings is more reliable, more secure, and likely also much easier than using this command line solution.
balpha
In fact, I just confirmed that command line is my only option in this case.
David Perron
Okay; then I suggest you ask a new question (going more to the mysql crowd), since there might might quite a few caveats to consider.
balpha
@David Concerning string interpolation: You have to use the string format syntax: "...%s..." % (day,) . $day or $sql won't cut it (we're not in Perl ;-).
ThomasH
"I just confirmed that command line is my only option" sounds like your manager has declared that simple Python is "too risky" or made some other such pronouncement.
S.Lott
+2  A: 

Try this:

import datetime
dt1 = datetime.date(2009, 1, 1)
dt2 = datetime.date(2009, 7, 1)
dt = dt1
while dt <= dt2:
    print dt.strftime("%Y-%m-%d")
    dt += datetime.timedelta(days=1)

You say you are restricted to an older version of Python. If you don't have the datetime module (Python < 2.3), then you can also do:

import time
dt1 = time.mktime(time.strptime('2009-01-01', '%Y-%m-%d'))
dt2 = time.mktime(time.strptime('2009-07-01', '%Y-%m-%d'))
ONE_DAY = 86400
dt = dt1
while dt <= dt2:
    print time.strftime('%Y-%m-%d', time.gmtime(dt))
    dt += ONE_DAY
Daniel Pryden
+2  A: 
In [1]: from dateutil.relativedelta import *

In [2]: from datetime import *

In [3]: aday = datetime.today()

In [4]: nextweek = aday+relativedelta(weeks=1)

In [5]: while aday<nextweek:
   ...:     print datetime.strftime(aday,format='%Y-%b-%d')
   ...:     aday+=relativedelta(days=1)
   ...:     
   ...:     
    #Output
2009-Aug-03
2009-Aug-04
2009-Aug-05
2009-Aug-06
2009-Aug-07
2009-Aug-08
2009-Aug-09

While you can do, most of the stuff about datetime using the stdlib, (IMO) dateutil lets you do it faster and better.

Lakshman Prasad
I took time off to finish this, yet this answer is not even acknowledged, just because a few people answered it seconds before; it sucks!
Lakshman Prasad
Looks more like they were an hour ahead, rather than mere seconds...
ThomasH