Reputation: 764
I've been given thee task to get all dates for payments. Let's say I have two dates:
date1 = date(2021,1,1)
date2 = date(2021,1,31)
So the logic is this: if it is the start of the month (date1
) the payment should be for that month and if the date is the end of the month (date2
) the payment should go for the next month. I have code like this:
from datetime import datetime, date
from dateutil.relativedelta import *
date1 = date(2021,1,1)
date2 = date(2021,1,31)
m = [date1, date2]
for date in m:
date += relativedelta(months=1)
print(date.strftime('%Y/%m/%d'))
And the result is:
2021/02/01
2021/02/28
Which is basically correct, but I need the result to be like this:
2021/01 # payment for 1st month
2021/02 # payment for 2nd month
How can I do that?
Solution thanks to @deceze:
from datetime import datetime, date, timedelta
from dateutil.relativedelta import *
from calendar import monthrange
date1 = date(2021,1,1)
date2 = date(2021,1,31)
m = [date1, date2]
for date in m:
if monthrange(date.year, date.month)[1] == date.day:
date += timedelta(days=1)
print(date.strftime('%Y/%m'))
elif monthrange(date.year, date.month)[1] != date.day:
print(date.strftime('%Y/%m'))
Upvotes: 0
Views: 123
Reputation: 522250
I assume you want this?
from datetime import date, timedelta
from calendar import monthrange
date2 = date(2021, 1, 31)
if monthrange(date2.year, date2.month)[1] == date2.day:
date2 += timedelta(days=1)
If the day falls on the last day of a month (check with calendar.monthrange
), increment it by one to be the first day of next month.
Upvotes: 1