Creating a range of dates in Python


Question

I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?

import datetime

a = datetime.datetime.today()
numdays = 100
dateList = []
for x in range (0, numdays):
    dateList.append(a - datetime.timedelta(days = x))
print dateList
1
284
6/14/2009 6:03:59 PM

Accepted Answer

Marginally better...

base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]
388
7/29/2019 7:43:25 AM

Pandas is great for time series in general, and has direct support for date ranges.

For example pd.date_range():

import pandas as pd
datelist = pd.date_range(pd.datetime.today(), periods=100).tolist()

It also has lots of options to make life easier. For example if you only wanted weekdays, you would just swap in bdate_range.

See http://pandas.pydata.org/pandas-docs/stable/timeseries.html#generating-ranges-of-timestamps

In addition it fully supports pytz timezones and can smoothly span spring/autumn DST shifts.

EDIT by OP:

If you need actual python datetimes, as opposed to Pandas timestamps:

pd.date_range(end = pd.datetime.today(), periods = 100).to_pydatetime().tolist()

This uses the "end" parameter to match the original question, but if you want descending dates:

pd.date_range(pd.datetime.today(), periods=100).to_pydatetime().tolist()

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon