Skip to content

Instantly share code, notes, and snippets.

@Johnetordoff
Created August 28, 2024 15:47
Show Gist options
  • Save Johnetordoff/817ce30cac6ca18ee59ce55ee56b294f to your computer and use it in GitHub Desktop.
Save Johnetordoff/817ce30cac6ca18ee59ce55ee56b294f to your computer and use it in GitHub Desktop.
import unittest
from datetime import datetime
def is_leap_year(year):
return (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0)
def calculate_leap_age(birthdate, current_date):
start_year = birthdate.year if birthdate.month > 2 else birthdate.year + 1
end_year = current_date.year - 1 if current_date.month < 2 or (current_date.month == 2 and current_date.day < 29) else current_date.year
return sum(is_leap_year(year) for year in range(start_year, end_year + 1))
class TestLeapAgeCalculator(unittest.TestCase):
def test_birth_before_leap_year(self):
birthdate = datetime(1987, 3, 1) # Born right after Feb 1987
current_date = datetime(2024, 8, 28)
self.assertEqual(calculate_leap_age(birthdate, current_date), 9) # 1988, 1992, ..., 2020
def test_birth_on_leap_day(self):
birthdate = datetime(1988, 2, 29)
current_date = datetime(2024, 8, 28)
self.assertEqual(calculate_leap_age(birthdate, current_date), 9) # 1992, 1996, ..., 2020
def test_birth_after_leap_day(self):
birthdate = datetime(1988, 3, 1)
current_date = datetime(2024, 8, 28)
self.assertEqual(calculate_leap_age(birthdate, current_date), 9) # 1992, 1996, ..., 2020
def test_birth_end_of_year(self):
birthdate = datetime(1987, 12, 31)
current_date = datetime(2024, 8, 28)
self.assertEqual(calculate_leap_age(birthdate, current_date), 9) # 1988, 1992, ..., 2020
def test_current_date_before_leap_day(self):
birthdate = datetime(1987, 1, 1)
current_date = datetime(2024, 2, 28)
self.assertEqual(calculate_leap_age(birthdate, current_date), 9) # 1988, 1992, ..., 2020
def test_current_date_on_leap_day(self):
birthdate = datetime(1987, 1, 1)
current_date = datetime(2024, 2, 29)
self.assertEqual(calculate_leap_age(birthdate, current_date), 10) # 1988, 1992, ..., 2024
def test_no_leap_years(self):
birthdate = datetime(1989, 3, 1)
current_date = datetime(1989, 12, 31)
self.assertEqual(calculate_leap_age(birthdate, current_date), 0) # No leap years in this range
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment