Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I calculate the date six months from the current date using the datetime Python module?

I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?

The reason I want to generate a date 6 months from the current date is to produce a review date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data.

like image 647
RailsSon Avatar asked Feb 13 '09 15:02

RailsSon


People also ask

How do I convert a datetime to a specific date in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I find the months between two dates in Python?

Use the relativedelta. months + relativedelta. years * 12 formula to get the total months between two dates.


1 Answers

I found this solution to be good. (This uses the python-dateutil extension)

from datetime import date from dateutil.relativedelta import relativedelta  six_months = date.today() + relativedelta(months=+6) 

The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)

$ date(2010,12,31)+relativedelta(months=+1)   datetime.date(2011, 1, 31)  $ date(2010,12,31)+relativedelta(months=+2)   datetime.date(2011, 2, 28) 
like image 102
Mahendra Avatar answered Sep 30 '22 17:09

Mahendra