1

Interestingly, I have searched a lot of questions but I cannot find just a simple answer to this question. Or I do find an answer but it won't allow me the flexibility to alter the format of the dates I require.

If I have a specified start and end date like this:

start = '2015-08-01' #YYY-MM-DD
end = '2020-07-06'

Is there a simple way using datetime in python to create a list of dates between these dates that adhere to this format of YYY-MM-DD? And if so, how can I subsequently reverse this list so list[0] is equal to today?

4 Answers 4

2

Here's a way using list comprehensions, which is far faster than the loop examples, and doesn't require any external libraries.

from datetime import date, timedelta

start = '2015-08-01'
end = '2020-07-06'

start_date = date.fromisoformat(start)
end_date = date.fromisoformat(end)

date_range = [
    # end_date - timedelta(days=i)  # For date objects
    (end_date - timedelta(days=i)).isoformat()  # For ISO-8601 strings
    for i
    in range((end_date - start_date).days)
]
reverse_range = list(reversed(date_range))

print(date_range[0])
print(reverse_range[0])

Output

2020-07-06
2015-08-02
Sign up to request clarification or add additional context in comments.

5 Comments

reverse_range = list(reversed(date_range)) seems to be a bit of a drag, when there's date_range[::-1] :)
would there be a way I can store the elements in the list as datetime objects rather than strings?
@Johnny Just remove the .isoformat() and the parenthesis from the date calculation at the beginning of the list comprehension. date.isoformat() returns an ISO-8601 string representation of the datetime object.
@PrateekDewan Using built-in methods designed specifically for a purpose is almost always better. To the casual observer, your proposed solution is incomprehensible, and you'd have to understand the nuances of Python to understand what's happening there. Using reversed() self-documents what is happening.
Aye aye, Cap'n!
1

You can also use pandas

import pandas as pd

start = '2015-08-01' #YYY-MM-DD
end = '2020-07-06'

pd.date_range(start, end)

# to start from today

pd.date_range(pd.Timestamp.today(), end)


You can also create a range with your desired frequency

pd.date_range(start, end, freq='14d') # every 14 dayes
pd.date_range(start, end, freq='H') # hourly and etc

2 Comments

Short and sweet! Just that the question asks for a solution using datetime.
Just as an alternative @PrateekDewan
1

The datetime.timedelta() function will help here. Try this:

import datetime
dates = []
d = datetime.date(2015,8,1)
while d <= datetime.date(2020,7,6):
    dates.append(datetime.datetime.strftime(d,'%Y-%m-%d'))
    d += datetime.timedelta(days=1)

This will populate the list dates, which will look like this:

['2015-08-01', '2015-08-02', '2015-08-03', .... , '2020-07-04', '2020-07-05', '2020-07-06']

EDIT:

Just use dates.append(d) instead of dates.append(datetime.datetime.strftime(d,'%Y-%m-%d')) to get a list of datetime.date objects instead of strings.

Reversing a list is pretty straight-forward in Python:

dates = dates[::-1]

After the above, dates[0] will be '2020-07-06'.

Comments

0

something like this ?

import datetime

def date_range(start, end):
    r = (end+datetime.timedelta(days=1)-start).days
    return [start+datetime.timedelta(days=i) for i in range(r)]

start = datetime.date(2015,01,01)
end = datetime.date(2020,07,06)
dateList = date_range(start, end)
print '\n'.join([str(date) for date in dateList])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.