Creating a range of dates in Python Creating a range of dates in Python python python

Creating a range of dates in Python


Marginally better...

base = datetime.datetime.today()date_list = [base - datetime.timedelta(days=x) for x in range(numdays)]


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

For example pd.date_range():

import pandas as pdfrom datetime import datetimedatelist = pd.date_range(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 date range documentation

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:

import pandas as pdfrom datetime import datetimepd.date_range(end = datetime.today(), periods = 100).to_pydatetime().tolist()#ORpd.date_range(start="2018-09-09",end="2020-02-02")

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

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


Get range of dates between specified start and end date (Optimized for time & space complexity):

import datetimestart = datetime.datetime.strptime("21-06-2014", "%d-%m-%Y")end = datetime.datetime.strptime("07-07-2014", "%d-%m-%Y")date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]for date in date_generated:    print date.strftime("%d-%m-%Y")


matomo