Skip to content

Instantly share code, notes, and snippets.

@vubon
Created July 21, 2018 23:36
Show Gist options
  • Save vubon/c5af7eb7199653aff5b5a3fde0389049 to your computer and use it in GitHub Desktop.
Save vubon/c5af7eb7199653aff5b5a3fde0389049 to your computer and use it in GitHub Desktop.
Finding last date from a dates range by Python
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