Skip to content
Related Articles
Open in App
Not now

Related Articles

Creating a list of range of dates in Python

Improve Article
Save Article
  • Last Updated : 13 Sep, 2022
Improve Article
Save Article

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.

Examples:

Input : test_date = datetime.datetime(1997, 1, 4), K = 5

Output : [datetime.datetime(1997, 1, 4), datetime.datetime(1997, 1, 5), datetime.datetime(1997, 1, 6), datetime.datetime(1997, 1, 7), datetime.datetime(1997, 1, 8)]

Explanation : 5 dates after 4 January are extracted in list.

Creating a list of dates using pd.date_range

In this method, we will use pandas date_range to create a list of ranges of dates in Python.

Python3




import datetime
import pandas as pd
 
# initializing date
test_date = datetime.datetime.strptime("01-7-2022", "%d-%m-%Y")
 
# initializing K
K = 5
 
date_generated = pd.date_range(test_date, periods=K)
print(date_generated.strftime("%d-%m-%Y"))

Output:

Index(['01-07-2022', '02-07-2022', '03-07-2022', '04-07-2022', '05-07-2022'], dtype='object')

Creating a list of dates 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.

Python3




import datetime
 
# initializing date
test_date = datetime.datetime(1997, 1, 4)
 
# initializing K
K = 5
 
# timedelta() gets successive dates with
# appropriate difference
res = [test_date + datetime.timedelta(days=idx) for idx in range(K)]
 
# printing result
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, 0)]

Creating a list of dates using Python Loop

In this, we perform a similar task as the above function, using a generator to perform the task of Date successions.

Python3




import datetime
 
start = datetime.date(2022,8,12)
 
# initializing K
K = 5
 
res = []
 
for day in range(k):
    date = (start + datetime.timedelta(days = day)).isoformat()
    res.append(date)
     
# printing result
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']

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!