Created
January 27, 2011 17:39
-
-
Save shawnchin/798866 to your computer and use it in GitHub Desktop.
custom time delta that attempts returns deltas in terms of years, months, days
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from datetime import timedelta | |
def time_delta(d1,d2): | |
""" | |
Returns time delta as the following tuple: | |
("before|after|same", "years", "months", "days") | |
""" | |
if d1 == d2: | |
return ("same",0,0,0) | |
# d1 before or after d2? | |
if d1 > d2: | |
ba = "after" | |
d1,d2 = d2,d1 # swap so d2 > d1 | |
else: | |
ba = "before" | |
years = d2.year - d1.year | |
months = d2.month - d1.month | |
days = d2.day - d1.day | |
# adjust for -ve days/months | |
if days < 0: | |
# get last day of month for month before d1 | |
pre_d1 = d1 - timedelta(days=d1.day) | |
days = days + pre_d1.day | |
months = months - 1 | |
if months < 0: | |
months = months + 12 | |
years = years - 1 | |
return (ba, years, months, days) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment