Home > Software design >  Expand list of dates by incrementing dates by one day in python
Expand list of dates by incrementing dates by one day in python

Time:01-19

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?

CodePudding user response:

You will need to import a library:

import datetime

First convert the strings to dates using datetime.strptime. The important part of the code is the datetime.timedelta, is a function to sum days, month or years to a date. Create a new list to store the dates 1, and then alternate the old date with the new date, that was calculated.

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

for date in dates:
    tempDate = datetime.datetime.strptime(date, '%Y-%m-%d')
    tempDate = tempDate   datetime.timedelta(days=1)
    tempDate = tempDate.strftime('%Y-%m-%d')
    newDates.append(date)
    newDates.append(tempDate)

print(newDates)

Result:

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

CodePudding user response:

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']

CodePudding user response:

With datetime.timedelta class to get the needed difference/offset in days:

from datetime import datetime, timedelta
from itertools import chain

dates = ['2022-01-01', '2022-01-08', '2022-01-21']
dates_inc = list(chain.from_iterable((d, str((timedelta(days=1)   datetime.strptime(d, "%Y-%m-%d")).date())) 
                                     for d in dates))
print(dates_inc)

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