2

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

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

6 Comments

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 = a 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 I 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!
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.
In fact, I just confirmed that command line is my only option in this case.
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.
@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 ;-).
|
2

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

Comments

2
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.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.