I want to calculate 6 month before date in python.So is there any problem occurs at dates (example 31 august).Can we solve this problem using timedelta() function.can we pass months like date=now - timedelta(days=days) instead of argument days.
timedelta
does not support months, but you can try using dateutil.relativedelta
for your calculations , which do support months.
Example -
>>> from dateutil import relativedelta
>>> from datetime import datetime
>>> n = datetime.now()
>>> n - relativedelta.relativedelta(months=6)
datetime.datetime(2015, 1, 30, 10, 5, 32, 491815)
>>> n - relativedelta.relativedelta(months=8)
datetime.datetime(2014, 11, 30, 10, 5, 32, 491815)
If you are only interested in what the month was 6 months ago then try this:
import datetime
month = datetime.datetime.now().month - 6
if month < 1:
month = 12 + month # At this point month is 0 or a negative number so we add
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