Last active
July 5, 2022 10:55
-
-
Save ramhiser/989263a7a136601e3723 to your computer and use it in GitHub Desktop.
Python generator to construct range of dates
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 datetime, timedelta | |
def date_range(start, end, step=7, date_format="%m-%d-%Y"): | |
""" | |
Creates generator with a range of dates. | |
The dates occur every 7th day (default). | |
:param start: the start date of the date range | |
:param end: the end date of the date range | |
:param step: the step size of the dates | |
:param date_format: the string format of the dates inputted and returned | |
""" | |
start = datetime.strptime(str(start), date_format) | |
end = datetime.strptime(str(end), date_format) | |
num_days = (end_date - start_date).days | |
for d in xrange(0, num_days + step, step): | |
date_i = start + timedelta(days=d) | |
yield date_i.strftime(date_format) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!