In Excel, you can generate a series of consecutive dates with a simple drag. In Python, you can do something similar with the datetime and timedelta modules. Whether you want intervals of one hour, one day, or one month, you can do it.

It’s actually quite simple. Sometimes your brain just gets stuck and you don’t think of doing it this way. By using timedelta together with a loop, you can generate a series of datetime strings and store them in an array. The following example generates an array of times at 5-second intervals:

import datetime

dt = datetime.datetime(2010, 12, 1,)
end = datetime.datetime(2010, 12, 30)
step = datetime.timedelta(days=1)

result = []

while dt < end:
  result.append(dt.strftime('%Y-%m-%d %H:%M:%S'))
  dt += step

print(result)

Of course, you can also rewrite it with a list comprehension to speed things up, or use a generator depending on the situation.

import datetime as dt

print([dt.date(2017,1,1)+dt.timedelta(days=i) for i in range(30)])

But if we’re talking about the most convenient option, it’s the date_range function provided by Pandas. It wraps the generator for creating a time series into a function for you. It performs well and saves space. Unlike generating values with a loop, which can take a while when the range is large, let’s look at an example:

# Generate 100 items in daily units, starting from 2017/1/1

import pandas as pd

result = pd.date_range('2017/1/1 10:00:00', periods=100, freq='D')

print(result.tolist())
print(result[0:5].to_pydatetime())

for dt in result:
  print(dt.to_pydatetime())

For freq, you can use values other than D. For example, H is hour and M is month. Or refer to the table below:

AliasDescription
Bbusiness day frequency
Ccustom business day frequency (experimental)
Dcalendar day frequency
Wweekly frequency
Mmonth end frequency
SMsemi-month end frequency (15th and end of month)
BMbusiness month end frequency
CBMcustom business month end frequency
MSmonth start frequency
SMSsemi-month start frequency (1st and 15th)
BMSbusiness month start frequency
CBMScustom business month start frequency
Qquarter end frequency
BQbusiness quarter endfrequency
QSquarter start frequency
BQSbusiness quarter start frequency
Ayear end frequency
BAbusiness year end frequency
ASyear start frequency
BASbusiness year start frequency
BHbusiness hour frequency
Hhourly frequency
T, minminutely frequency
Ssecondly frequency
L, msmilliseconds
U, usmicroseconds
Nnanoseconds