runnig

addDays

Mar 27th, 2024
835
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. import datetime
  2.  
  3.  
  4. def isLeapYear(year):
  5.     return (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0)
  6.  
  7. monthDays = {
  8.     1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31,
  9. }
  10. def daysInMonth(year, month):
  11.     if month == 2 and isLeapYear(year):
  12.         return 29
  13.     return monthDays[month]
  14.  
  15. def addDays(year:int, month:int, day:int, nDays:int) -> tuple[int, int, int]:
  16.     outpYear, outpMonth, outpDay = year, month, day
  17.  
  18.     # First, increment full years
  19.     if nDays >= 365:
  20.         years = nDays // 365
  21.         outpYear += years
  22.         nDays -= years * 365
  23.  
  24.     # Second, increment months
  25.     while nDays > 0:
  26.         monthDays = daysInMonth(outpYear, outpMonth)
  27.         # nDays beyond this month
  28.         if nDays >= monthDays:
  29.             nDays -= monthDays
  30.             outpMonth += 1
  31.         # output date in the next month
  32.         elif nDays + outpDay > monthDays:
  33.             s = nDays + outpDay
  34.             s -= monthDays
  35.             outpDay = s
  36.             nDays = 0
  37.             outpMonth += 1
  38.         else:
  39.             outpDay += nDays
  40.             nDays = 0
  41.         # in the next month
  42.         if outpMonth > 12: # next year
  43.             outpMonth = 1
  44.             outpYear += 1
  45.         if outpDay == 0:
  46.             outpDay = 1
  47.     return outpYear, outpMonth, outpDay
  48.  
  49.  
  50. for nDays in range(0, 365*3):
  51.     computed = addDays(1970, 1, 1, nDays)
  52.     computed_dt = datetime.date(computed[0], computed[1], computed[2])
  53.     expected = datetime.date(1970, 1, 1) + datetime.timedelta(days=nDays)
  54.     if computed_dt != expected:
  55.         print(nDays, 'disagree', computed_dt, expected)
Advertisement
Add Comment
Please, Sign In to add comment