Last active
December 14, 2015 04:18
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 'begin' | |
print begin | |
for month in by_month(begin, end): | |
print ' ', month | |
print end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment