如果你不关心的一个月内的日子,你可以这样做:
在同一个月内,例如
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
我的日期是不同的年份,我在想如果有一个相当于'datediff(月,日期1,日期2)的SQL' – unclegood