Generate vectors of datetime in Python and Matlab

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
  • Matlab ≥ R2014b datetime
  • Matlab ≤ R2014a and GNU Octave


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 datetime import datetime, timedelta
import typing

def datetime_range(start: datetime, end: datetime,
                   step: timedelta) -> typing.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))

With Numpy datetime64 generate 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.

Matlab ≥ R2014b

Matlab R2014b introduced datetime that is strongly encouraged over the ambiguous datenum() supported by old Matlab and GNU Octave.

dt = datetime(2019, 12, 1):datetime(2020, 4, 1)

Matlab ≤ R2014a and GNU Octave

GNU Octave does yet have a datetime class. To be compatible with old Matlab versions and GNU Octave, generate a range of datenum times like:

function times = datetimerange(tstart, tend, ts)
% generate a vector range of time using datenum time
% ts: seconds

validateattributes(tstart, {'numeric'}, {'scalar', 'positive'})
validateattributes(tend, {'numeric'}, {'scalar', 'positive'})
validateattributes(ts, {'numeric'}, {'scalar', 'positive'})

t0 = datenum(t0);
t1 = datenum(t1);

times = t0:ts/86400:t1;