1

I am trying to find a more concise way to produce a range of dates between two values. I want this function to be similar to the built in range function in python.

#Range Function
>>>range(1,5)
[1,2,3,4]

This is what I currently have written:

def as_datetime(date_string):
    try:
        return datetime.datetime.strptime(date_string, '%d/%m/%Y')
    except ValueError:
        # The date string was invalid
        return None

x = []
start_date = as_datetime('12/07/2013')
end_date = as_datetime('16/07/2013')

total_days = (end_date - start_date).days + 1

for day_number in range(total_days):
    cd = (start_date + dt.timedelta(days = day_number)).date()
    x.append(cd.strftime('%d/%m/%Y'))

#Output
>>>Print x
['12/07/2013', '13/07/2013', '14/07/2013', '15/07/2013', '16/07/2013']

To me it seems like a lot of code for a basic function. That would be great if you could assist me in finding/amending some code to perform this action.

user3374113
  • 593
  • 1
  • 7
  • 20
  • I'm using a dd/mm/yyyy format for entry and all the others are using (yyyy,dd,mm) and its this incompatibility that I am having the most trouble. – user3374113 May 30 '14 at 03:58
  • 1
    @user3374113 the conversion to/from strings has nothing to do with the question you asked. You need to update the question to make it clear what you're really asking for. – Mark Ransom May 30 '14 at 04:01

1 Answers1

2

You can write this trivially with a generator.

from datetime import datetime, timedelta

def daterange(start, end):
    current = start

    while current < end:
        yield current
        current += timedelta(days = 1)

To optimize a bit, you should save that timedelta object for reuse. Use the generator like this:

start = datetime(2014, 1, 1)
end   = datetime(2014, 1, 4)

for d in daterange(start, end):
    print d

You can improve this implementation by creating a class and providing __iter__. That way, you also offer __len__, __getitem__ indexing, etc.

salezica
  • 74,081
  • 25
  • 105
  • 166