Skip to content

Instantly share code, notes, and snippets.

@daleobrien
Last active December 14, 2015 04:18
Show Gist options
  • Save daleobrien/5026738 to your computer and use it in GitHub Desktop.
Save daleobrien/5026738 to your computer and use it in GitHub Desktop.
Iterate between two months between 2 dates. Note some months will may have less days than the first month, in that case, the last day of the month will be returned.
#!/usr/bin/env python
from datetime import date
from calendar import monthrange
def by_month(start, end):
day_of_month = start.day
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)
d = min(monthrange(y, m + 1)[1], day_of_month)
day = date(y, m + 1, d)
if day >= start and day <= end:
yield day
if __name__ == "__main__":
begin = date(2012, 1, 31)
end = date(2013, 3, 20)
print
print 'begin'
print begin
for month in by_month(begin, end):
print ' ', month
print end
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment