Home > Back-end >  Python Generate Dates based on N days
Python Generate Dates based on N days

Time:07-16

The below code is a list-comprehension of all possible dates between a lower and upper bound:

from datetime import date, timedelta

d1 = date(2022,1,1)
d2 = date(2022,12,31)

dates = [d1   timedelta(days=x) for x in range((d2-d1).days   1)]

However, instead of mentioning d2; I want to mention the n number of days I want generated:

from datetime import date, timedelta

d1 = date(2022,1,1)
n = 3

dates = []

dates:

2022-01-01
2022-01-02
2022-01-03

CodePudding user response:

You can create a for-loop and generate date with timedelta and store it in a list.

>>> [d1 timedelta(days=i) for i in range(n)]
[datetime.date(2022, 1, 1),
 datetime.date(2022, 1, 2),
 datetime.date(2022, 1, 3)]

>>> [(d1 timedelta(days=i)).strftime('%Y-%m-%d') for i in range(n)]
['2022-01-01', '2022-01-02', '2022-01-03']

Explanation:

from datetime import date, timedelta

d1 = date(2022,1,1)
n = 3

dates = []
for i in range(n):
    tmp = d1   timedelta(days=i)
    dates.append(tmp.strftime('%Y-%m-%d'))
    
    # Or store as <class 'datetime.date'>
    # dates.append(tmp)

print(dates)

Output:

['2022-01-01', '2022-01-02', '2022-01-03']

CodePudding user response:

easy:

from datetime import date, timedelta

N_DAYS = 30
d1 = date(2022,1,1)
d2 = d1  timedelta(days=N_DAYS)

dates = [d1   timedelta(days=x) for x in range((d2-d1).days   1)]
converted_data = list(map(lambda date:date.strftime('%Y-%m-%d'),dates))
print(converted_data)


CodePudding user response:

If you don't mind using an external library, pandas.date_range is quite simple and versatile:

import pandas as pd

d1 = '2022-1-1'
# or 
# d1 = datetime.date(2022,1,1)
n = 3

out = pd.date_range(d1, periods=n, freq='D').strftime('%Y-%m-%d').to_list()

output: ['2022-01-01', '2022-01-02', '2022-01-03']

  • Related