Skip to content

Instantly share code, notes, and snippets.

@richardbowden
Last active August 29, 2015 14:14
Show Gist options
  • Save richardbowden/529aaa80b5202c7673c4 to your computer and use it in GitHub Desktop.
Save richardbowden/529aaa80b5202c7673c4 to your computer and use it in GitHub Desktop.
get years and months from two dates
from datetime import datetime
def get_length_of_time(start_date, end_date=None, days_in_year=365, days_in_month=30):
"""
start_date and end_date should be a datetime object with the day of month
always being 1, as all we need is to calc years and months between two dates
"""
if end_date == None:
d = date.today()
end_date = datetime(d.year, d.month, 1)
if start_date == end_date:
return 0,0
if start_date > end_date:
raise Exception('Start date cannot be greater than end date')
total_days = (end_date - start_date).days
years, r = divmod(total_days, days_in_year)
months = round(r / days_in_month)
return years, months
import unittest
from datetime import datetime
import date_tools
class LengthOfTimeCalc(unittest.TestCase):
def test_should_return_1_year_and_0_months(self):
start_date = datetime(2001,1,1)
end_date = datetime(2002,1,1)
years, months = date_tools.get_length_of_time(start_date, end_date)
self.assertEqual(years, 1, msg="Years should = 1")
self.assertEqual(months, 0, msg="Months should = 0")
def test_should_return_2_years_and_4_months(self):
start_date = datetime(2001,1,1)
end_date = datetime(2003,5,1)
years, months = date_tools.get_length_of_time(start_date, end_date)
self.assertEqual(years, 2, msg="Years should = 1")
self.assertEqual(months, 4, msg="Months should = 0")
def test_start_and_end_date_are_equal_should_return_0_0(self):
start_date = datetime(2001,1,1)
end_date = datetime(2001,1,1)
years, months = date_tools.get_length_of_time(start_date, end_date)
self.assertEqual(years, 0, msg="Years should = 0")
self.assertEqual(months, 0, msg="Months shold = 0")
def test_raise_execption_if_start_date_is_greater_than_end_date(self):
start_date = datetime(2001,1,1)
end_date = datetime(2000,1,1)
with self.assertRaises(Exception):
years, months = date_tools.get_length_of_time(start_date, end_date=end_date)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment