Generate vectors of datetime in Python

Generating a range of datetime data is a common data analysis and simulation task. Here we show examples of generating datetime vectors for Python datetime and numpy.datetime64

Python datetime

Python datetime is often used as timezone-naïve with UTC as the assumed timezone. This custom avoids ambiguities when working with Pandas and Numpy, which are foundational for Python data science.

Generate a range of Python datetime like:

from __future__ import annotation
from datetime import datetime, timedelta

def datetime_range(start: datetime, end: datetime, step: timedelta) -> list[datetime]:
    """like range() for datetime"""
    return [start + i * step for i in range((end - start) // step)]

dt = datetime_range(datetime(2019, 12, 1), datetime(2020, 4, 1), timedelta(days=1))

Numpy datetime64

Numpy datetime64 generates a range of times like:

dt = numpy.arange('2019-12-01', '2020-04-01', dtype='datetime64[D]')

Pandas has the date_range function to generate time vectors.