Use the relativedelta. months + relativedelta. years * 12 formula to get the total months between two dates.
The Gregorian calendar has 4 months that are 30 days long and 7 months that are 31 days long.
You should use calendar.monthrange
:
>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)
Just to be clear, monthrange
supports leap years as well:
>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)
As @mikhail-pyrev mentions in a comment:
First number is the weekday of the first day of the month, the second number is the number of days in said month.
Alternative solution:
>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29
Just for the sake of academic interest, I did it this way...
(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With