Last active
September 18, 2018 23:39
-
-
Save alejio/5d1eea26db7894387f2ef4a343f9fa43 to your computer and use it in GitHub Desktop.
Python,Pandas: Calculate difference in months between two dates
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
# Inspired from here http://stackoverflow.com/questions/7015587/python-difference-of-2-datetimes-in-months | |
from datetime import datetime, timedelta | |
from calendar import monthrange | |
def monthdelta(df): | |
d1 = df[0] | |
d2 = df[1] | |
delta = 0 | |
while True: | |
mdays = monthrange(d1.year, d1.month)[1] | |
d1 += timedelta(days=mdays) | |
if d1 <= d2: | |
delta += 1 | |
else: | |
break | |
# use with df['months_difference'] = df[['date1', 'date2']].apply(monthdelta, axis=1) | |
return delta |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment