Creating date ranges in Python

I want to create a list of dates, starting today, and then returning any number of days, such as 100 days in my example. Is there a better way?

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 building

Yes, reinvent the wheel. As long as you search on the forum, you will get something like this:

from dateutil import rrule
from datetime import datetime

list(rrule.rrule(rrule.DAILY,count=100,dtstart=datetime.now()))

#2 building

Overall, Pandas It is very suitable for time series and directly supports date range.

for example pd.date_range() :

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

It also has many options to make life easier. For example, if you only want workdays, just exchange bdate_range .

see also Date range document

In addition, it fully supports pytz time zones and can smoothly span spring / autumn DST offsets.

OP editor:

If you need the actual python date time instead of the panda timestamp:

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

This uses the "end" parameter to match the original problem, but if you want to use dates in descending order:

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

#3 building

Gets the date range between the specified start and end dates (optimized for time and space complexity):

import datetime

start = 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")

#4 building

Matplotlib related

from matplotlib.dates import drange
import datetime

base = datetime.date.today()
end  = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
l = drange(base, end, delta)

#5 building

import datetime    
def date_generator():
    cur = base = datetime.date.today()
    end  = base + datetime.timedelta(days=100)
    delta = datetime.timedelta(days=1)
    while(end>base):
        base = base+delta
        print base

date_generator()

Tags: Spring Python

Posted on Fri, 20 Mar 2020 13:41:05 -0400 by vincent30000