Creating a list of range of dates in Python
Given a date, the task is to write a Python program to create a list of a range of dates with the next k dates starting from the current date. For example, if the given date is 4th January 1997 and k is 5, the output should be a list containing 4th January 1997, 5th January 1997, 6th January 1997, 7th January 1997 and 8th January 1997. This can be achieved using various methods available in Python.
Using pd.date_range
In this method, we will use pandas date_range to create a list of ranges of dates in Python. It is ideal for users working with data analysis or time series. This method is clean, readable and leverages the powerful pandas library to handle date ranges efficiently.
import datetime
import pandas as pd
td = datetime.datetime.strptime("01-7-2022", "%d-%m-%Y")
k = 5
d = pd.date_range(td, periods=k)
print(d.strftime("%d-%m-%Y"))
Output
Index(['01-07-2022', '02-07-2022', '03-07-2022', '04-07-2022', '05-07-2022'], dtype='object')
Explanation: Generates a range of k consecutive dates from a given start date using Pandas’ date_range, which returns a DatetimeIndex.
Using timedelta() + list comprehension
In this, we get to add consecutive deltas to day using timedelta() and list comprehension is used to iterate through the required size and construct the required result.
import datetime
td = datetime.datetime(1997, 1, 4)
k = 5
res = [td + datetime.timedelta(days=idx) for idx in range(k)]
print("Next k dates list : " + str(res))
Output
Next k dates list : [datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0), datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0), datetime.datetime(1997, 1, 8, 0...
Explanation: This code generates a list of dates by adding timedelta(days=idx) to the starting date using list comprehension.
Using Python Loop
In this, we perform a similar task as the above function, using a generator to perform the task of Date successions.
import datetime
td = datetime.date(2022,8,12)
k = 5
res = []
for day in range(k):
date = (td + datetime.timedelta(days = day)).isoformat()
res.append(date)
print("Next k dates list: " + str(res))
Output
Next k dates list: ['2022-08-12', '2022-08-13', '2022-08-14', '2022-08-15', '2022-08-16']
Explanation: Uses a simple loop to calculate each date, convert it to ISO string format and append it to a list.
Using while Loop with timedelta()
This method is best when both a start and end date are known. This method gives all dates within the range, regardless of how many days.
from datetime import datetime, timedelta
sd = datetime(2022, 3, 1)
ed = datetime(2022, 3, 10)
d = []
while sd <= ed:
d.append(sd.strftime("%d-%m-%Y"))
sd += timedelta(days=1)
print(d)
Output
['01-03-2022', '02-03-2022', '03-03-2022', '04-03-2022', '05-03-2022', '06-03-2022', '07-03-2022', '08-03-2022', '09-03-2022', '10-03-2022']
Explanation: This code generates all dates between two specified dates using a while loop and timedelta(days=1).
Using Generator with yield and timedelta()
This method is best for memory efficiency when generating a large number of dates. This method yields one date at a time instead of storing all in memory.
import datetime
def date_range_4(td, k):
i = 0
while i < k:
yield td + datetime.timedelta(days=i)
i += 1
td = datetime.datetime(1997, 1, 4)
k = 5
d = list(date_range_4(td, k))
print(d)
Output
[datetime.datetime(1997, 1, 4, 0, 0), datetime.datetime(1997, 1, 5, 0, 0), datetime.datetime(1997, 1, 6, 0, 0), datetime.datetime(1997, 1, 7, 0, 0), datetime.datetime(1997, 1, 8, 0, 0)]
Explanation: This code implements a generator that yields each date in the range one-by-one, making it suitable for large datasets or lazy evaluation.
Related Articles: