-1

This is my code:

MYDATE = []
start_date = "2011-01-01"
stop_date = "2013-05-01"

start = start_date.strftime("%Y-%m-%d")
stop = stop_date.strftime("%Y-%m-%d")
for r in .......:
    MYDATE.append((r,r))

How can I iterate over Date betweet start_date and stop_date?

user3505844
  • 35
  • 1
  • 1
  • 2
  • 6
    Using what interval? Years, months, days, seconds? Bit more info needed I think. – elParaguayo Apr 07 '14 at 08:22
  • 1
    I'd just add 1 month to the start date inside a `while` loop e.g. `while newdate < stop:` I don't know if there's an easy way to add months, but I did see this: http://stackoverflow.com/questions/4130922/how-to-increment-datetime-month-in-python – elParaguayo Apr 07 '14 at 08:26
  • See this old question: http://stackoverflow.com/questions/1060279/iterating-through-a-range-of-dates-in-python – Ber Apr 07 '14 at 08:52
  • 2
    How do you manage to use `strftime()` on a string object? – Stefan van den Akker Apr 07 '14 at 08:57
  • Also related: [How to increment datetime month in python](http://stackoverflow.com/questions/4130922/how-to-increment-datetime-month-in-python) – Mp0int Apr 07 '14 at 09:00

2 Answers2

15

Well it depends on how you wish to iterate. By days? by months? Using timedelta will solve your problem.

from datetime import datetime

start_date = "2011-01-01"
stop_date = "2013-05-01"

start = datetime.strptime(start_date, "%Y-%m-%d")
stop = datetime.strptime(stop_date, "%Y-%m-%d")

from datetime import timedelta
while start < stop:
    start = start + timedelta(days=1)  # increase day one by one

Another approach to itearete through months is using relativedelta

from dateutil.relativedelta import relativedelta
start = start + relativedelta(months = +1)
Mp0int
  • 18,172
  • 15
  • 83
  • 114
0

What about timedelta?

start = datetime.now()
end = start + timedelta(days=10)

tmp = start

while tmp < end:
    print tmp
    tmp = tmp + timedelta(days=1) # replace the interval at will

prints

2014-04-07 10:42:14.943790
2014-04-08 10:42:14.943790
2014-04-09 10:42:14.943790
2014-04-10 10:42:14.943790
2014-04-11 10:42:14.943790
2014-04-12 10:42:14.943790
2014-04-13 10:42:14.943790
2014-04-14 10:42:14.943790
2014-04-15 10:42:14.943790
2014-04-16 10:42:14.943790
Danstahr
  • 4,190
  • 22
  • 38
  • This does not answer the question as the frequency required is monthly and timedelta does not support month according to the documentation – Grimmy Apr 07 '14 at 08:50