Expand list of dates by incrementing dates by one day in python

In Python I have a list of dates as strings:

dates = ['2022-01-01', '2022-01-08', '2022-01-21']

I would like to increment these dates by one day and add them to this list, like so:

dates_new = ['2022-01-01', '2022-01-02', '2022-01-08', '2022-01-09', '2022-01-21', '2022-01-22']

What is the best way to achieve this?

>Solution :

Try:

from datetime import datetime, timedelta

one_day = timedelta(days=1)
dates = ["2022-01-01", "2022-01-08", "2022-01-21"]

out = []
for d in dates:
    x = datetime.strptime(d, "%Y-%m-%d")
    out.append(d)
    out.append((x + one_day).strftime("%Y-%m-%d"))

print(out)

Prints:

['2022-01-01', '2022-01-02', '2022-01-08', '2022-01-09', '2022-01-21', '2022-01-22']

Leave a Reply