Add months_diff

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-10-28 16:20:39 +02:00
parent d6a889c5e1
commit 52de9547d9

22
snippets/months_diff.md Normal file
View File

@ -0,0 +1,22 @@
---
title: months_diff
tags: date,beginner
---
Calculates the month difference between two dates.
- Subtract `start` from `end` and use `datetime.timedelta.days` to get the day difference.
- Divide by `30` and use `math.ceil()` to get the difference in months (rounded up).
```py
from math import ceil
def months_diff(start, end):
return ceil((end - start).days / 30)
```
```py
from datetime import date
months_diff(date(2020, 10, 28), date(2020, 11, 25)) # 1
```