Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

6 month before date in python [duplicate]

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.

like image 865
Ashith Avatar asked Dec 14 '22 12:12

Ashith


2 Answers

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)
like image 112
Anand S Kumar Avatar answered Jan 03 '23 02:01

Anand S Kumar


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
like image 38
Eric Bulloch Avatar answered Jan 03 '23 01:01

Eric Bulloch