Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a month iterator

Tags:

python

I would like to create a python function that would allow me to iterate over the months from a start point to a stop point. For example it would look something like

def months(start_month, start_year, end_month, end_year): 

Calling months(8, 2010, 3, 2011) would return:

((8, 2010), (9, 2010), (10, 2010), (11, 2010), (12, 2010), (1, 2011), (2, 2011), (3, 2011)) 

The function could just return a tuple of tuples, but I would love to see it as a generator (ie using yield).

I've checked the calendar python module and it doesn't appear to provide this functionality. I could write a nasty for loop to do it easily enough, but I'm interested to see how gracefully it could be done by a pro.

Thanks.

like image 350
dgel Avatar asked Apr 20 '11 17:04

dgel


People also ask

How do you iterate over months 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 loop a date?

One way to loop through a date range with JavaScript is to use a while loop. We can create variables for the start and end dates. Then we can increment the start date until it reaches the end date. We have the start and end variables with the start and end date respectively.

How do you iterate time in python?

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.

What is the meaning of loop in Python?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.


1 Answers

The calendar works like this.

def month_year_iter( start_month, start_year, end_month, end_year ):     ym_start= 12*start_year + start_month - 1     ym_end= 12*end_year + end_month - 1     for ym in range( ym_start, ym_end ):         y, m = divmod( ym, 12 )         yield y, m+1 

All multiple-unit things work like this. Feet and Inches, Hours, Minutes and Seconds, etc., etc. The only thing that's not this simple is months-days or months-weeks because months are irregular. Everything else is regular, and you need to work in the finest-grained units.

like image 66
S.Lott Avatar answered Sep 19 '22 07:09

S.Lott