python 计算两个日期之间年数差月数差
时间: 2024-01-25 21:04:28 浏览: 182
计算两个日期间的年月日差
在Python中,计算两个日期之间的年数差和月数差可以使用datetime模块来实现。可以通过计算两个日期的年份和月份的差值来得到结果。下面是一个示例代码:
```python
import datetime
def get_date_diff(start_date, end_date):
start_year = start_date.year
start_month = start_date.month
end_year = end_date.year
end_month = end_date.month
year_diff = end_year - start_year
month_diff = end_month - start_month
if month_diff < 0:
year_diff -= 1
month_diff += 12
return year_diff, month_diff
# 示例使用
start_date = datetime.date(2020, 1, 15)
end_date = datetime.date(2021, 9, 30)
year_diff, month_diff = get_date_diff(start_date, end_date)
print("年数差:", year_diff)
print("月数差:", month_diff)
```
阅读全文