How to Iterating Days

Iterating through a range of dates in Python

Why are there two nested iterations? For me it produces the same list of data with only one iteration:

for single_date in (start_date + timedelta(n) for n in range(day_count)):
print ...

And no list gets stored, only one generator is iterated over. Also the "if" in the generator seems to be unnecessary.

After all, a linear sequence should only require one iterator, not two.

Update after discussion with John Machin:

Maybe the most elegant solution is using a generator function to completely hide/abstract the iteration over the range of dates:

from datetime import date, timedelta

def daterange(start_date, end_date):
for n in range(int((end_date - start_date).days)):
yield start_date + timedelta(n)

start_date = date(2013, 1, 1)
end_date = date(2015, 6, 2)
for single_date in daterange(start_date, end_date):
print(single_date.strftime("%Y-%m-%d"))

NB: For consistency with the built-in range() function this iteration stops before reaching the end_date. So for inclusive iteration use the next day, as you would with range().

How to iterate through range of Dates in Java?

Well, you could do something like this using Java 8's time-API, for this problem specifically java.time.LocalDate (or the equivalent Joda Time classes for Java 7 and older)

for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1))
{
...
}

I would thoroughly recommend using java.time (or Joda Time) over the built-in Date/Calendar classes.

How do I loop through a date range?

Well, you'll need to loop over them one way or the other. I prefer defining a method like this:

public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for(var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}

Then you can use it like this:

foreach (DateTime day in EachDay(StartDate, EndDate))
// print it or whatever

In this manner you could hit every other day, every third day, only weekdays, etc. For example, to return every third day starting with the "start" date, you could just call AddDays(3) in the loop instead of AddDays(1).

How to iterate from a custom day in the past to today?

The sample uses for loop. But, I try to use recursion.

from datetime import timedelta, date

def getdate(date):
print (date)
if date == date.today(): return
getdate(date+timedelta(1))

start_date = date(2018, 1, 1)
getdate(start_date)

Python: Iterate over all days in a month

The calendar module is designed to display calendars. You are better off using calendar.monthlen in combination with datetime.date itself to get your iterator, if you are looking for something straightforward:

def date_iter(year, month):
for i in range(1, calendar.monthlen(year, month) + 1):
yield date(year, month, i)

for d in date_iter(2019, 12):
print(d)

You can of course write the whole thing as a one-liner:

for d in (date(2019, 12, i) for i in range(1, calendar.monthlen(2019, 12) + 1)):
print(d)

The monthlen attribute appears to be a public, but undocumented attribute of calendar in Python 3.7. It is analogous to the second element of monthrange, so you can replace it with monthrange(year, month)[1] in the code above.

How to iterate over a timespan after days, hours, weeks and months?

Use dateutil and its rrule implementation, like so:

from dateutil import rrule
from datetime import datetime, timedelta

now = datetime.now()
hundredDaysLater = now + timedelta(days=100)

for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater):
print dt

Output is

2008-09-30 23:29:54
2008-10-30 23:29:54
2008-11-30 23:29:54
2008-12-30 23:29:54

Replace MONTHLY with any of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Replace dtstart and until with whatever datetime object you want.

This recipe has the advantage for working in all cases, including MONTHLY. Only caveat I could find is that if you pass a day number that doesn't exist for all months, it skips those months.

Java: How to iterate over days in a Period object

Even though Jon Skeet's answer is the right answer, an easy workaround would be

LocalDate currentStart=LocalDate.from(start);
LocalDate currentEnd=LocalDate.from(end.plusDays(1));//end is inclusive
do{
// do what you want with currentStart
//....
currentStart=currentStart.plusDays(1);
}while (!currentStart.equals(currentEnd));

Iterating over date in python

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)


Related Topics



Leave a reply



Submit