Created
March 17, 2015 18:27
-
-
Save gdmachado/7815608bf539f3a058fb to your computer and use it in GitHub Desktop.
Python period generator
This file contains 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
from datetime import datetime | |
import calendar | |
def genDatePeriods(startDate, endDate, format='%Y-%m-%d'): | |
dt1 = datetime.strptime(startDate, format) | |
dt2 = datetime.strptime(endDate, format) | |
for year in range(dt1.year, dt2.year + 1): | |
for month in range(1, 13): | |
day0 = dt1.day if month == dt1.month and year == dt1.year else 1 | |
day1 = dt2.day if month == dt2.month and year == dt2.year else calendar.monthrange(year, month)[1] | |
if (year == dt1.year and month < dt1.month) or (year == dt2.year and month > dt2.month): | |
continue | |
else: | |
d0 = (year, month, day0) | |
d1 = (year, month, day1) | |
yield [datetime(*d).strftime(format) for d in [d0, d1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment