This covers how to get a date range in Python using only standard library modules.
"""
MIT LICENSED
(c) 2023 Jason R. Stevens, CFA
"""
from datetime import datetime, timedelta, timezone
from typing import Union
def date_range(
start_date: str, end: Union[str, None] = None
) -> List[datetime]:
"""Get a list of datetime objects between today and the given ISO string.
_Note: This function is not timezone-aware._"""
today = (
datetime.today()
if len(start_date) < 11
else datetime.now(tz=timezone.utc)
)
days_between = (today - datetime.fromisoformat(start_date)).days
return [today - timedelta(days=x) for x in range(1, days_between + 1)]
def test_date_range():
# "standard" usage
test_day = "2023-02-03"
test_dates = date_range(test_day)
assert len(test_dates)
assert isinstance(test_dates, list)
assert isinstance(test_dates[0], datetime)
# ensure today isn't included (non-inclusive ending date)
today = str(datetime.now(tz=timezone.utc))
assert not len(date_range(today))
# ensure a single day is included for "yesterday"
yesterday = datetime(get_current_date()) - timedelta(days=1)
assert len(date_range(str(yesterday))) == 1
dates: List[datetime] = date_range('2023-02-16')
print(dates)