Created
July 21, 2018 23:36
-
-
Save vubon/c5af7eb7199653aff5b5a3fde0389049 to your computer and use it in GitHub Desktop.
Finding last date from a dates range by Python
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
from datetime import date, timedelta, datetime | |
def month_in_range(start_date, end_date): | |
"""Get the last day of every month in a range between two datetime values. | |
Return a generator | |
""" | |
start_month = start_date.month | |
end_months = (end_date.year-start_date.year)*12 + end_date.month | |
date_obj = [] | |
for month in range(start_month, end_months + 2): | |
# Get years in the date range, add it to the start date's year | |
year = (month-1)//12 + start_date.year | |
month = (month-1) % 12 + 1 | |
last_date = date(year, month, 1) - timedelta(days=1) | |
date_obj.append(last_date) | |
date_obj.pop(0) | |
yield date_obj | |
for dates in month_in_range(date(2018, 1, 1), datetime.now()): | |
for date in dates: | |
print(date) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment