Code Snippet: Generate a List of Dates

Here’s a short function you can use to generate a list of dates with the input parameters as ‘datestart’ and ‘dateend’.

def generate_dates(datestart_string, dateend_string):

        dates = []
        timepattern = '%Y-%m-%d'        

        ds = datetime.datetime.strptime(datestart_string, timepattern)
        de = datetime.datetime.strptime(dateend_string, timepattern)

        delta = datetime.timedelta(days=1)
        while ds <= de:
                dates.append(ds)
                ds += delta

        date_string = [datetime.datetime.strftime(date,timepattern) for date in dates]

        return date_string

So, print generate_dates(‘2011-01-01’, ‘2011-02-01’) will give you a list of dates as follows:

['2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04', '2011-01-05', '2011-01-06', '2011-01-07', '2011-01-08', '2011-01-09', '2011-01-10', '2011-01-11', '2011-01-12', '2011-01-13', '2011-01-14', '2011-01-15', '2011-01-16', '2011-01-17', '2011-01-18', '2011-01-19', '2011-01-20', '2011-01-21', '2011-01-22', '2011-01-23', '2011-01-24', '2011-01-25', '2011-01-26', '2011-01-27', '2011-01-28', '2011-01-29', '2011-01-30', '2011-01-31', '2011-02-01']
This function can also be written as a generator like so:
def generate_dates(datestart_string, dateend_string, timepattern="%Y-%m-%d"):
    ds = datetime.datetime.strptime(datestart_string, timepattern)
    de = datetime.datetime.strptime(dateend_string, timepattern)
    delta = datetime.timedelta(days=1)      

    while ds <= de:
            yield datetime.datetime.strftime(ds, timepattern)
            ds += delta

What is the difference you might ask? From what I understand, generators are more efficient or faster. In this case however, even if you were to set the start and end date to be 10 years apart, you will only have 3650 data points which is a small amount of data to be working with.

Advertisements

One thought on “Code Snippet: Generate a List of Dates

  1. Pingback: Building a Simple Reporting App in Django: Part 2 | pragmaticstartup

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s