views:

880

answers:

2

In my model, I have 2 datetime properties:

start_date
end_date

I would like to count the end date as a one week after the start_date.

How can I accomplish this?

+4  A: 
>>> import datetime
>>> start_date = datetime.datetime.now()
>>> end_date = start_date + datetime.timedelta(7)
>>> print end_date
Anurag Uniyal
basically just add 7 days to start-date, using timedelta class
Anurag Uniyal
+7  A: 

If you always want your end_date to be one week after the start_date, what you could do, is to make a custom save method for your model. Another option would be to use signals instead. The result would be the same, but since you are dealing with the models data, I would suggest that you go for the custom save method. The code for it would look something like this:

class ModelName(models.Model):
    ...

    def save(self):
        # Place code here, which is excecuted the same
        # time the ``pre_save``-signal would be
        self.end_date = self.start_date + datetime.timedelta(days=7)

        # Call parent's ``save`` function
        super(ModelName, self).save()

You can read about a bit about how the save method/signals is called in the django docs at: http://docs.djangoproject.com/en/dev/ref/models/instances/

googletorp
If you'll be using the datetime package, don't forget to read http://www.enricozini.org/2009/debian/using-python-datetime/
Mapio