Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I iterate over a timespan after days, hours, weeks or months?

Something like:

for date in foo(from_date, to_date, delta=HOURS):     print date 

Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.

like image 766
sverrejoh Avatar asked Sep 30 '08 15:09

sverrejoh


People also ask

How do you iterate over months between two dates in Python?

Method 2: rrule rrule is a package present in dateutil library and this package consists of a method also rrule which takes dtstart, until and specific time period as parameters which are start date, end date, and time period based on iteration respectively. Specific time periods are WEEKLY, MONTHLY, YEARLY, etc.

How do you iterate over a list length?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.

How do pandas iterate over dates?

We can use the date_range() function method that is available in pandas. It is used to return a fixed frequency DatetimeIndex. We can iterate to get the date using date() function.


1 Answers

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.

like image 120
Thomas Vander Stichele Avatar answered Oct 13 '22 17:10

Thomas Vander Stichele