1

The following code gives me a value error whenever I use months with 31 as the day like 31 July or 31 October. I'd like to know why I am getting the value error.

from datetime import datetime

date_format = "%Y-%m-%d"

def date_to_str(date_obj):
    return date_obj.strftime(date_format)

def str_to_date(str_obj):
    return datetime.strptime(str_obj, date_format)

first_date = str_to_date('2018-07-31')
tenure = 6
dates = [first_date]
for i in range(1, tenure):
    date = dates[i - 1]
    if date.month == 12:
        date = date.replace(year=date.year + 1, month=1)
    else:
        date = date.replace(month=date.month + 1)
    dates.append(date)
print(dates)
Mark Dickinson
  • 29,088
  • 9
  • 83
  • 120
  • 1
    What's your question? Are you asking _why_ you're getting a `ValueError`, or are you asking for ways to avoid the `ValueError`? What do you want one month on from 31st August to give, given that there's no such date as 31st September? – Mark Dickinson Sep 08 '18 at 10:50
  • 1
    Please provide the error as well. It will help the community understand the problem – Ilia Gilmijarow Sep 08 '18 at 10:51
  • Related: https://stackoverflow.com/questions/546321/how-do-i-calculate-the-date-six-months-from-the-current-date-using-the-datetime – jonrsharpe Sep 08 '18 at 10:53
  • What is the answer you're expecting? Is it `datetime.datetime(2019, 1, 31, 0, 0)` perhaps? (that being the end point of origin date + 6 months?) – Jon Clements Sep 08 '18 at 10:55
  • Correct. datetime.datetime(2019, 1, 31, 0, 0) is an expected output. –  Sep 08 '18 at 11:03
  • Do you understand why `datetime(2018, 8, 31).replace(month=9)` gives an error? – Mark Dickinson Sep 08 '18 at 11:47
  • @MarkDickinson think the OP might be better off using `dateutil` (using a `relativedelta` or `arrow` libraries to get an immediate end result... but yes, understanding why the current code doesn't work would make sense... – Jon Clements Sep 08 '18 at 11:57
  • @MarkDickinson Yes Sir I do know. Month number 9 does not have 31 days. –  Sep 08 '18 at 12:15
  • Thank You @MarkDickinson. I got it now. The date vatiable iterates to 31st of every month. But the code fails when months like February and September are included in the iteration. It works well for months other months having total days equal to 31. –  Sep 08 '18 at 12:22

0 Answers0