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:
| Alias | Description |
|---|---|
| B | business day frequency |
| C | custom business day frequency (experimental) |
| D | calendar day frequency |
| W | weekly frequency |
| M | month end frequency |
| SM | semi-month end frequency (15th and end of month) |
| BM | business month end frequency |
| CBM | custom business month end frequency |
| MS | month start frequency |
| SMS | semi-month start frequency (1st and 15th) |
| BMS | business month start frequency |
| CBMS | custom business month start frequency |
| Q | quarter end frequency |
| BQ | business quarter endfrequency |
| QS | quarter start frequency |
| BQS | business quarter start frequency |
| A | year end frequency |
| BA | business year end frequency |
| AS | year start frequency |
| BAS | business year start frequency |
| BH | business hour frequency |
| H | hourly frequency |
| T, min | minutely frequency |
| S | secondly frequency |
| L, ms | milliseconds |
| U, us | microseconds |
| N | nanoseconds |