I have a list of dates
[datetime.date(2021, 1, 7), datetime.date(2021, 1, 14), datetime.date(2021, 1, 21), datetime.date(2021, 1, 28), datetime.date(2021, 2, 4), datetime.date(2021, 2, 11), datetime.date(2021, 2, 18), datetime.date(2021, 2, 25), datetime.date(2021, 3, 4), datetime.date(2021, 3, 10), datetime.date(2021, 3, 18), datetime.date(2021, 3, 25), datetime.date(2021, 4, 1), datetime.date(2021, 4, 8), datetime.date(2021, 4, 15), datetime.date(2021, 4, 22), datetime.date(2021, 4, 29), datetime.date(2021, 5, 6), datetime.date(2021, 5, 12), datetime.date(2021, 5, 20), datetime.date(2021, 5, 27), datetime.date(2021, 6, 3)]
and I want to decrease every dates at least 2 days like -
datetime.date(2021, 1, 7) = datetime.date(2021, 1, 6), datetime.date(2021, 1, 5)
And this is my whole code -
before_dates = []
for dates in expiry_list:
Date = pd.date_range(pd.to_datetime(dates), periods=3).date
before_dates.append(Date)
at this time I'm using this code which is increment dates -
Date = pd.date_range(pd.to_datetime(dates), periods=3).date
But this code is just increment dates to 3 days - Example -
[array([datetime.date(2021, 1, 7), datetime.date(2021, 1, 8),
datetime.date(2021, 1, 9)], dtype=object),
array([datetime.date(2021, 1, 14), datetime.date(2021, 1, 15),
datetime.date(2021, 1, 16)], dtype=object),
array([datetime.date(2021, 1, 21), datetime.date(2021, 1, 22),
datetime.date(2021, 1, 23)], dtype=object),
array([datetime.date(2021, 1, 28), datetime.date(2021, 1, 29),
datetime.date(2021, 1, 30)], dtype=object)]
But I want this output as in this Decrement format - Example -
[array([datetime.date(2021, 1, 7), datetime.date(2021, 1, 6),
datetime.date(2021, 1, 5)], dtype=object),
array([datetime.date(2021, 1, 14), datetime.date(2021, 1, 13),
datetime.date(2021, 1, 12)], dtype=object),
array([datetime.date(2021, 1, 21), datetime.date(2021, 1, 20),
datetime.date(2021, 1, 19)], dtype=object),
array([datetime.date(2021, 1, 28), datetime.date(2021, 1, 27),
datetime.date(2021, 1, 26)], dtype=object)]
So please help me to solve this problem.
CodePudding user response:
You can use the List Comprehensions directly
import datetime
dates = [datetime.date(2021, 1, 7), datetime.date(2021, 1, 14), datetime.date(2021, 1, 21), datetime.date(2021, 1, 28), datetime.date(2021, 2, 4), datetime.date(2021, 2, 11), datetime.date(2021, 2, 18), datetime.date(2021, 2, 25), datetime.date(2021, 3, 4), datetime.date(2021, 3, 10), datetime.date(2021, 3, 18), datetime.date(2021, 3, 25), datetime.date(2021, 4, 1), datetime.date(2021, 4, 8), datetime.date(2021, 4, 15), datetime.date(2021, 4, 22), datetime.date(2021, 4, 29), datetime.date(2021, 5, 6), datetime.date(2021, 5, 12), datetime.date(2021, 5, 20), datetime.date(2021, 5, 27), datetime.date(2021, 6, 3)]
new_dates = [[data - datetime.timedelta(days=i) for i in range(3)] for data in dates]
print(new_dates)