Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading