0

I want to add a number of days to a given date without using any library I did this part of code :

   Days_in_Month = [31, 27, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

if isBisextile(year):
   Days_in_Month[1] = 28

days = int(input("Enter number of days:\n"))

while days > 0:

   if isBisextile(year):
       Days_in_Month[1] = 28
   date += 1

   if date > int(Days_in_Month[month-1]):
       month += 1
       if month > 12:
           year += 1
           month = 1
       date = 1
   days -= 1


print("{}/{}/{}".format(date, month, year))

If I test with, for example:

Enter a date:
2/7/1980
Enter number of days:
1460

It yields 2/7/1984 instead of 1/7/1984

Does someone have idea why I have plus one day ?

2
  • 3
    how is your isBisextile function works ? Commented Nov 24, 2019 at 23:28
  • 1
    Creating a library like this is a good way to learn but, and I can't stress this enough, should not be done for code you are relying on. Assuming this is a given but want to put it in for posterity. I have seen lots of bugs from people trying to recreate datetime libraries. It's typically error prone and every language has datetime functions to rely on. Commented Nov 24, 2019 at 23:58

1 Answer 1

1

This appears to have fixed your issue:

Days_in_Month[1] should be 28 or 29, not 27 or 28 and it needed to be corrected both ways for each year.

I wrote my own isBisextile() which is obviously not fully compliant with all of the rules of leap-years that are % 100 or % 400 but I assume you have that covered in your version that you haven't shown us.

year = 1980
month = 7
date = 2

Days_in_Month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isBisextile(year):
    return True if year%4 == 0 else False

if isBisextile(year):
   Days_in_Month[1] = 29

days = int(input("Enter number of days:\n"))

while days > 0:

   if isBisextile(year):
       Days_in_Month[1] = 29
   else:
       Days_in_Month[1] = 28

   date += 1

   if date > int(Days_in_Month[month-1]):
       month += 1
       if month > 12:
           year += 1
           month = 1
       date = 1
   days -= 1


print("{}/{}/{}".format(date, month, year))

For 2/7/1980 and number of days: 1460 it gives 1/7/1984 as expected.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.