Last active
August 4, 2016 21:48
-
-
Save graham-thomson/c4c7d4ee7831bc9e32584b6935e6b5f9 to your computer and use it in GitHub Desktop.
Function returns a list of string dates in YYYY-MM-DD format between and including start and end date.
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
import datetime as dt | |
def list_of_dates(start_date, end_date): | |
""" | |
Function returns a list of string dates in YYYY-MM-DD format between and including start and end date. | |
:param start_date: Start date string in YYYY-MM-DD format | |
:param end_date: End date string in YYYY-MM-DD format | |
:return: List of date strings | |
""" | |
start_date = dt.datetime.strptime(start_date, "%Y-%m-%d") | |
end_date = dt.datetime.strptime(end_date, "%Y-%m-%d") | |
try: | |
assert(start_date < end_date) | |
dates_to_return = [] | |
d0 = start_date | |
while d0 <= end_date: | |
dates_to_return.append(d0.strftime("%Y-%m-%d")) | |
d0 += dt.timedelta(days=1) | |
return dates_to_return | |
except AssertionError: | |
raise AttributeError("Start date not less than end date.") | |
# usage: print list_of_dates("2016-01-01", "2016-01-12") | |
# ['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04', '2016-01-05', '2016-01-06', | |
# '2016-01-07', '2016-01-08', '2016-01-09', '2016-01-10', '2016-01-11', '2016-01-12'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment