Skip to content

Instantly share code, notes, and snippets.

@thinkjrs
Last active February 19, 2023 01:32
Show Gist options
  • Save thinkjrs/e913e57485e8f725813731e19fa77a22 to your computer and use it in GitHub Desktop.
Save thinkjrs/e913e57485e8f725813731e19fa77a22 to your computer and use it in GitHub Desktop.
Date range in Python

Date Range in Python

This covers how to get a date range in Python using only standard library modules.

The code

"""
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)]

Unit test

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

Usage example

dates: List[datetime] = date_range('2023-02-16')
print(dates)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment