あなたは月内の日を気にしない場合は、次のように行うことができます。
date1.year * 12 + date1.month - (date2.year * 12 + date2.month)
同じ月の日付'2016-12-31 'と'2016-12-1'は0を返します。
月の中の日を計算したい場合は、指定されるまでの月の割合を計算できます日。例えば。月に30日がある場合、最初の日の分数は0/30で、最後の日の分数は29/30です。 このコードスニペットは、それを行います。
from calendar import monthrange
def get_frac_of_month(date):
# monthrange returns a tuple where the second entry is the number of days in the month
return 1. * (date.day - 1)/monthrange(date.year, date.month)[1]
def get_month_diff(date1, date2):
return date1.year * 12 + date1.month + get_frac_of_month(date1) - (date2.year * 12 + date2.month + get_frac_of_month(date2))
print get_month_diff(date1, date2)
出力に含まが
6.16129032258
月になる標準単位ではありません。月に30日かかるとしたら、 '(date1 - date2).days/30'とすることができます – ayhan
あなたのすべての日付は同じ年ですか? – doctorlove
私の日付は異なる年ですが、SQLの同等の 'datediff(month、date1、date2)'があると思っていました – unclegood