-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?

5
  • 6
    Using what interval? Years, months, days, seconds? Bit more info needed I think. Commented Apr 7, 2014 at 8: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: stackoverflow.com/questions/4130922/… Commented Apr 7, 2014 at 8:26
  • See this old question: stackoverflow.com/questions/1060279/… Commented Apr 7, 2014 at 8:52
  • 2
    How do you manage to use strftime() on a string object? Commented Apr 7, 2014 at 8:57
  • Also related: How to increment datetime month in python Commented Apr 7, 2014 at 9:00

2 Answers 2

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

Comments

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

1 Comment

This does not answer the question as the frequency required is monthly and timedelta does not support month according to the documentation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.