Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date 6 months into the future

I am using the datetime Python module in django. I am looking to calculate the date if the expiry date is less than or equal to 6 months from the current date.

The reason I want to generate a date 6 months from the current date is to set an alert that will highlight the field/column in which that event occurs. I dont know if my question is clear. I have been reading about timedelta function but cant really get my head round it. I am trying to write an if statement to statisfy this condition. Anyone able to help me please? Am a newbie to django and python.

like image 303
roykasa Avatar asked Feb 18 '13 10:02

roykasa


1 Answers

There are two approaches, one only slightly inaccurate, one inaccurate in a different way:

  • Add a datetime.timedelta() of 365.25 / 2 days (average year length divided by two):

      import datetime
      sixmonths = datetime.datetime.now() + datetime.timedelta(days=365.25/2)
    

    This method will give you a datetime stamp 6 months into the future, where we define 6 monhs as exactly half a year (on average).

  • Use the external dateutil library, it has a excellent relativedelta class that will add 6 months based on calendar calculations to your current date:

      import datetime
      from dateutil.relativedelat import relativedelta
      sixmonths = datetime.datetime.now() + relativedelta(months=6)
    

    This method will give you a datetime stamp 6 months into the future, where the month component of the date has been forwarded by 6, and it'll take into account month boundaries, making sure not to cross them. August 30th plus 6 months becomes February 28th or 29th (leap years permitting), for example.

A demonstration could be helpful. In my timezone, at the time of posting, this translates to:

>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 2, 18, 12, 16, 0, 547567)
>>> now + datetime.timedelta(days=365.25/2)
datetime.datetime(2013, 8, 20, 3, 16, 0, 547567)
>>> now + relativedelta(months=6)
datetime.datetime(2013, 8, 18, 12, 16, 0, 547567)

So there is a 1 day and 15 hour difference between the two methods.

The same methods work fine with datetime.date objects too:

>>> today = datetime.date.today()
>>> today
datetime.date(2013, 2, 18)
>>> today + datetime.timedelta(days=365.25/2)
datetime.date(2013, 8, 19)
>>> today + relativedelta(months=6)
datetime.date(2013, 8, 18)

The half-year timedelta becomes a teensy less accurate when applied to dates only (the 5/8th day component of the delta is ignored now).

like image 103
Martijn Pieters Avatar answered Sep 29 '22 19:09

Martijn Pieters